local-operator-ui 0.42.1 → 0.42.2
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/out/main/index.js +496 -2
- package/out/renderer/assets/{_basePickBy-bSYERMaj.js → _basePickBy-BA9uepHv.js} +1 -1
- package/out/renderer/assets/{_baseUniq-XXFAU1GI.js → _baseUniq-CVACH15m.js} +1 -1
- package/out/renderer/assets/{agent-details-page-FzlOCzmB.js → agent-details-page-xNTNJ7kP.js} +2 -2
- package/out/renderer/assets/{agent-hub-page-V0BSbGBu.js → agent-hub-page-B-zE3Ln0.js} +2 -2
- package/out/renderer/assets/{agents-page-DHu2xkX8.js → agents-page-BeZQ1S7f.js} +3 -3
- package/out/renderer/assets/approvalsOverlay-BBr6f98F.css +1 -0
- package/out/renderer/assets/approvalsOverlay-BmSmF8Ga.js +1 -0
- package/out/renderer/assets/{arc-DJDaWivU.js → arc-DYIy54Kn.js} +1 -1
- package/out/renderer/assets/architectureDiagram-IEHRJDOE-CmfaKw-J.js +36 -0
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-BGcgINKS.js → blockDiagram-JOT3LUYC-bQf90tJr.js} +2 -2
- package/out/renderer/assets/{book-open-CTVKA12r.js → book-open-iGajLTwQ.js} +1 -1
- package/out/renderer/assets/browser-page-B63Z8oE2.js +1 -0
- package/out/renderer/assets/browser-webauthn-prompt-DX5l4JNA.js +1 -0
- package/out/renderer/assets/{building-2-Bky--3rC.js → building-2-bjja6JTC.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-Dxg4lYU_.js → c4Diagram-VJAJSXHY-BxIFIYVW.js} +2 -2
- package/out/renderer/assets/channel-Blax8LQd.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-Bbfr_o8o.js → chunk-4BMEZGHF-C2LQ_mlD.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-CnzwrRQc.js → chunk-A2AXSNBT-BKH53MbC.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-DIq6FzSQ.js → chunk-AEK57VVT-CuB5dlAL.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-BhQgOD8q.js → chunk-D6G4REZN-CECeg3Wn.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-1bt5bhUU.js → chunk-RZ5BOZE2-D-zkJWYc.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-BV47b5FV.js → chunk-XZIHB7SX-DstteBuH.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-DA1IQG_V.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-DA1IQG_V.js +1 -0
- package/out/renderer/assets/clone-mVVuLCMS.js +1 -0
- package/out/renderer/assets/{console-mirror-CfrfbIAp.js → console-mirror-gqAdwBWl.js} +2 -2
- package/out/renderer/assets/consoleCapture-BQQVRcXT.js +1 -0
- package/out/renderer/assets/{conversation-input-sync-DKNOMiIp.js → conversation-input-sync-grry80zS.js} +41 -41
- package/out/renderer/assets/dagre-OKDRZEBW-D6RBxeJd.js +4 -0
- package/out/renderer/assets/diagram-SSKATNLV--xUREIPn.js +43 -0
- package/out/renderer/assets/diagram-VNBRO52H-BYjZ86BM.js +24 -0
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-jChbtQ8s.js → erDiagram-Q7BY3M3F-CmajcoOO.js} +2 -2
- package/out/renderer/assets/{error-boundary-CQf4hj53.js → error-boundary-DfTTKe65.js} +3 -3
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-C-ETkl-L.js → flowDiagram-4HSFHLVR-CtQab7ap.js} +2 -2
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-D42KlmKC.js → ganttDiagram-APWFNJXF-CuKez3d0.js} +2 -2
- package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-D9QOaWwN.js +65 -0
- package/out/renderer/assets/{graph-BdWT-wGp.js → graph-Ccifoj7G.js} +1 -1
- package/out/renderer/assets/{hash-C5NRsgoq.js → hash-EZ0d40pW.js} +1 -1
- package/out/renderer/assets/{heart-B_TWxEVI.js → heart-Bo3ZudoI.js} +1 -1
- package/out/renderer/assets/index-ByZv232u.css +1 -0
- package/out/renderer/assets/index-CLJ4-1jd.js +1 -0
- package/out/renderer/assets/index-DXk6NfLu.js +55 -0
- package/out/renderer/assets/index-Dw4hyitu.js +7 -0
- package/out/renderer/assets/{index-DiHe1x_2.js → index-LBzSehKd.js} +30 -30
- package/out/renderer/assets/infoDiagram-PH2N3AL5-DrTRSok5.js +2 -0
- package/out/renderer/assets/installer-B7DhTrnG.js +1 -0
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-Dvj6m4R3.js → journeyDiagram-U35MCT3I-YTjOSo-b.js} +2 -2
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-Dcs6Y93q.js → kanban-definition-NDS4AKOZ-C1UmNEaT.js} +4 -4
- package/out/renderer/assets/{layout--rr1tBJG.js → layout-CWPZ7noV.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-bX8ZD1oF.js → legacy-agents-page-ikCownYN.js} +2 -2
- package/out/renderer/assets/library-page-DBSSkZvn.js +157 -0
- package/out/renderer/assets/{mermaid.core-DlGo2U0C.js → mermaid.core-B_nZt27J.js} +5 -5
- package/out/renderer/assets/mesh-page-CgjL4HIw.js +1 -0
- package/out/renderer/assets/messages-Bswe4yCX.js +3 -0
- package/out/renderer/assets/mindmap-definition-ALO5MXBD-D-Y3n0RT.js +95 -0
- package/out/renderer/assets/mini-BdCfujvn.js +1 -0
- package/out/renderer/assets/{notebook-pen-BhmcgRiW.js → notebook-pen-BvZPJ7Yv.js} +1 -1
- package/out/renderer/assets/org-access-C1u_2VVY.js +1 -0
- package/out/renderer/assets/{org-surface-gate-BpVvnvxX.js → org-surface-gate-CyIC6H59.js} +1 -1
- package/out/renderer/assets/{page-header-rgKs_qEp.js → page-header-C9IFgiIB.js} +1 -1
- package/out/renderer/assets/{path-utils-Ch7GC1fh.js → path-utils-DC6z9Ymz.js} +17 -17
- package/out/renderer/assets/pieDiagram-IB7DONF6-BJ2PZoWa.js +30 -0
- package/out/renderer/assets/{projects-page-BQd1Mkfd.js → projects-page-CwwrR-j7.js} +2 -2
- package/out/renderer/assets/{publication-validation-DyFQAbl6.js → publication-validation-DAffiuLy.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-wWLUIv_7.js → quadrantDiagram-7GDLP6J5-Dpr0N86G.js} +2 -2
- package/out/renderer/assets/{radar-MK3ICKWK-DD77Iyne.js → radar-MK3ICKWK-CwLLK6fK.js} +1 -1
- package/out/renderer/assets/radient-auth-buttons-DN7K_uGZ.js +1 -0
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-Bu415aDm.js → requirementDiagram-KVF5MWMF-LI2fP6nJ.js} +2 -2
- package/out/renderer/assets/sankeyDiagram-QLVOVGJD-uUOWgFO1.js +10 -0
- package/out/renderer/assets/{schedules-page-BbKsER5C.js → schedules-page-Cf1PQGDR.js} +2 -2
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-BTO-WEKG.js → sequenceDiagram-X6HHIX6F-DperbqVG.js} +2 -2
- package/out/renderer/assets/{settings-page-qICF0iah.js → settings-page-CrnST8YF.js} +3 -3
- package/out/renderer/assets/smartart-qEAWtDlk.js +1 -0
- package/out/renderer/assets/stateDiagram-DGXRK772-RvRbNkSX.js +1 -0
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-fK1yLl-v.js +1 -0
- package/out/renderer/assets/{team-bridge-page-bhH2QlXH.js → team-bridge-page-BgcLwc5M.js} +2 -2
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-DcGupo97.js → timeline-definition-BDJGKUSR-CeQ3AsWj.js} +2 -2
- package/out/renderer/assets/{use-download-agent-mutation-DFoPvSHB.js → use-download-agent-mutation-C_zDZ6-1.js} +2 -2
- package/out/renderer/assets/{use-session-snapshot-BTmPQFBS.js → use-session-snapshot-BMDB4uZ0.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-Bqjodw42.js → xychartDiagram-VJFVF3MP-C6-d6maF.js} +5 -5
- package/out/renderer/browser-approvals-overlay.html +40 -0
- package/out/renderer/console-capture.html +6 -5
- package/out/renderer/index.html +8 -7
- package/out/renderer/installer.html +5 -4
- package/out/renderer/mini.html +8 -7
- package/package.json +6 -4
- package/out/renderer/assets/architectureDiagram-IEHRJDOE-BnQwEGXh.js +0 -36
- package/out/renderer/assets/browser-page-DFFwHX_q.js +0 -1
- package/out/renderer/assets/browser-webauthn-prompt-BWCI9wPS.js +0 -1
- package/out/renderer/assets/channel-EkPte-cJ.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-CFmWhsn7.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-CFmWhsn7.js +0 -1
- package/out/renderer/assets/clone-kXBnCGzD.js +0 -1
- package/out/renderer/assets/consoleCapture-BFG3Xbps.js +0 -1
- package/out/renderer/assets/dagre-OKDRZEBW-DA1nw5sl.js +0 -4
- package/out/renderer/assets/diagram-SSKATNLV-CVVTgWt7.js +0 -43
- package/out/renderer/assets/diagram-VNBRO52H-DHTfzrp0.js +0 -24
- package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-P9nmqR2u.js +0 -65
- package/out/renderer/assets/index-CdcfcuWL.js +0 -7
- package/out/renderer/assets/index-CgLFXaCJ.js +0 -57
- package/out/renderer/assets/index-CjtdK8OG.css +0 -1
- package/out/renderer/assets/index-uHBz6pD4.js +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-CGwg5naH.js +0 -2
- package/out/renderer/assets/installer-BPsqzY3G.js +0 -1
- package/out/renderer/assets/library-page-DeVhJsuP.js +0 -157
- package/out/renderer/assets/mesh-page-BOHX8DXw.js +0 -1
- package/out/renderer/assets/mindmap-definition-ALO5MXBD-D2k6gjX2.js +0 -95
- package/out/renderer/assets/mini-D58TB08i.js +0 -1
- package/out/renderer/assets/org-access-BIqG4bO9.js +0 -1
- package/out/renderer/assets/pieDiagram-IB7DONF6-TkoS-yEQ.js +0 -30
- package/out/renderer/assets/radient-auth-buttons-DOUeYctr.js +0 -1
- package/out/renderer/assets/sankeyDiagram-QLVOVGJD-DicsIJ4H.js +0 -10
- package/out/renderer/assets/smartart-drXgC4cZ.js +0 -1
- package/out/renderer/assets/stateDiagram-DGXRK772-DRBkBLBL.js +0 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CCFNyg2W.js +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{b as aa,r as v,t as ae,j as Xu,D as qu}from"./index-CgLFXaCJ.js";var ne;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(const a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var fi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(fi||(fi={}));const j=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wt=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?j.promise:typeof Map<"u"&&e instanceof Map?j.map:typeof Set<"u"&&e instanceof Set?j.set:typeof Date<"u"&&e instanceof Date?j.date:j.object;default:return j.unknown}},I=ne.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"]),ef=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ve extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return s(this),r}static assert(t){if(!(t instanceof Ve))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ve.create=e=>new Ve(e);const wn=(e,t)=>{let n;switch(e.code){case I.invalid_type:e.received===j.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ne.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ne.joinValues(e.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ne.joinValues(e.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ne.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.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}"`:ne.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case I.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 I.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 I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=t.defaultError,ne.assertNever(e)}return{message:n}};let ll=wn;function tf(e){ll=e}function Vr(){return ll}const Kr=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...s,path:i,message:c}},nf=[];function P(e,t){const n=Vr(),r=Kr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===wn?void 0:wn].filter(s=>!!s)});e.common.issues.push(r)}class Le{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return B;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return Le.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return B;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const B=Object.freeze({status:"aborted"}),hn=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),pi=e=>e.status==="aborted",hi=e=>e.status==="dirty",Jt=e=>e.status==="valid",Qn=e=>typeof Promise<"u"&&e instanceof Promise;function Yr(e,t,n,r){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 dl(e,t,n,r,s){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 N;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}));var Bn,Gn;class mt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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 ca=(e,t)=>{if(Jt(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 Ve(e.common.issues);return this._error=n,this._error}}};function Q(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:s}}class J{get description(){return this._def.description}_getType(t){return wt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Le,ctx:{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Qn(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 r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},i=this._parseSync({data:t,path:s.path,parent:s});return ca(s,i)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:s});return Jt(i)?{value:i.value}:{issues:s.common.issues}}catch(i){!((r=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(i=>Jt(i)?{value:i.value}:{issues:s.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(Qn(s)?s:Promise.resolve(s));return ca(r,i)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=t(s),c=()=>i.addIssue({code:I.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ct({schema:this,typeName:F.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 ht.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return at.create(this)}promise(){return kn.create(this,this._def)}or(t){return er.create([this,t],this._def)}and(t){return tr.create(this,t,this._def)}transform(t){return new ct({...Q(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new or({...Q(this._def),innerType:this,defaultValue:n,typeName:F.ZodDefault})}brand(){return new eo({typeName:F.ZodBranded,type:this,...Q(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new ar({...Q(this._def),innerType:this,catchValue:n,typeName:F.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return _r.create(this,t)}readonly(){return cr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const rf=/^c[^\s-]{8,}$/i,sf=/^[0-9a-z]+$/,of=/^[0-9A-HJKMNP-TV-Z]{26}$/i,af=/^[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,cf=/^[a-z0-9_-]{21}$/i,lf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,df=/^[-+]?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)?)??$/,uf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ff="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ms;const pf=/^(?:(?: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])$/,hf=/^(?:(?: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])$/,mf=/^(([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]))$/,gf=/^(([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])$/,yf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_f=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ul="((\\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])))",vf=new RegExp(`^${ul}$`);function fl(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 bf(e){return new RegExp(`^${fl(e)}$`)}function pl(e){let t=`${ul}T${fl(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 wf(e,t){return!!((t==="v4"||!t)&&pf.test(e)||(t==="v6"||!t)&&mf.test(e))}function Sf(e,t){if(!lf.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function kf(e,t){return!!((t==="v4"||!t)&&hf.test(e)||(t==="v6"||!t)&&gf.test(e))}class ot extends J{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==j.string){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.string,received:i.parsedType}),B}const r=new Le;let s;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")uf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ms||(Ms=new RegExp(ff,"u")),Ms.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")af.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")cf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")rf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")sf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")of.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"ulid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),P(s,{validation:"url",code:I.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"regex",code:I.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.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)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?pl(i).test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?vf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?bf(i).test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?df.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?wf(t.data,i.version)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Sf(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?kf(t.data,i.version)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?yf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?_f.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:I.invalid_string,...N.errToObj(r)})}_addCheck(t){return new ot({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.errToObj(t)})}datetime(t){var n,r;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:(r=t?.local)!==null&&r!==void 0?r:!1,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.errToObj(t))}trim(){return new ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ot({...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}}ot.create=e=>{var t;return new ot({checks:[],typeName:F.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Q(e)})};function Rf(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class Mt extends J{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)!==j.number){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.number,received:i.parsedType}),B}let r;const s=new Le;for(const i of this._def.checks)i.kind==="int"?ne.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Rf(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_finite,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new Mt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new Mt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&ne.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Mt.create=e=>new Mt({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...Q(e)});class Dt extends J{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)!==j.bigint)return this._getInvalidInput(t);let r;const s=new Le;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return P(n,{code:I.invalid_type,expected:j.bigint,received:n.parsedType}),B}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new Dt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new Dt({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}}Dt.create=e=>{var t;return new Dt({checks:[],typeName:F.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Q(e)})};class Jn extends J{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==j.boolean){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.boolean,received:r.parsedType}),B}return Ue(t.data)}}Jn.create=e=>new Jn({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...Q(e)});class Xt extends J{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==j.date){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.date,received:i.parsedType}),B}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_date}),B}const r=new Le;let s;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ne.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Xt({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}}Xt.create=e=>new Xt({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...Q(e)});class Qr extends J{_parse(t){if(this._getType(t)!==j.symbol){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.symbol,received:r.parsedType}),B}return Ue(t.data)}}Qr.create=e=>new Qr({typeName:F.ZodSymbol,...Q(e)});class Xn extends J{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.undefined,received:r.parsedType}),B}return Ue(t.data)}}Xn.create=e=>new Xn({typeName:F.ZodUndefined,...Q(e)});class qn extends J{_parse(t){if(this._getType(t)!==j.null){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.null,received:r.parsedType}),B}return Ue(t.data)}}qn.create=e=>new qn({typeName:F.ZodNull,...Q(e)});class Sn extends J{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Sn.create=e=>new Sn({typeName:F.ZodAny,...Q(e)});class Vt extends J{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}Vt.create=e=>new Vt({typeName:F.ZodUnknown,...Q(e)});class St extends J{_parse(t){const n=this._getOrReturnCtx(t);return P(n,{code:I.invalid_type,expected:j.never,received:n.parsedType}),B}}St.create=e=>new St({typeName:F.ZodNever,...Q(e)});class Jr extends J{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.void,received:r.parsedType}),B}return Ue(t.data)}}Jr.create=e=>new Jr({typeName:F.ZodVoid,...Q(e)});class at extends J{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==j.array)return P(n,{code:I.invalid_type,expected:j.array,received:n.parsedType}),B;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(P(n,{code:a?I.too_big:I.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(P(n,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(P(n,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new mt(n,a,n.path,c)))).then(a=>Le.mergeArray(r,a));const i=[...n.data].map((a,c)=>s.type._parseSync(new mt(n,a,n.path,c)));return Le.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new at({...this._def,minLength:{value:t,message:N.toString(n)}})}max(t,n){return new at({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new at({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(t){return this.min(1,t)}}at.create=(e,t)=>new at({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...Q(t)});function un(e){if(e instanceof _e){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(un(r))}return new _e({...e._def,shape:()=>t})}else return e instanceof at?new at({...e._def,type:un(e.element)}):e instanceof ht?ht.create(un(e.unwrap())):e instanceof Lt?Lt.create(un(e.unwrap())):e instanceof gt?gt.create(e.items.map(t=>un(t))):e}class _e extends J{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=ne.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==j.object){const d=this._getOrReturnCtx(t);return P(d,{code:I.invalid_type,expected:j.object,received:d.parsedType}),B}const{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof St&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new mt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof St){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(P(s,{code:I.unrecognized_keys,keys:c}),r.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=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new mt(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.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=>Le.mergeObjectSync(r,d)):Le.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return N.errToObj,new _e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,i,a,c;const l=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=N.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new _e({...this._def,unknownKeys:"strip"})}passthrough(){return new _e({...this._def,unknownKeys:"passthrough"})}extend(t){return new _e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new _e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new _e({...this._def,catchall:t})}pick(t){const n={};return ne.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new _e({...this._def,shape:()=>n})}omit(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new _e({...this._def,shape:()=>n})}deepPartial(){return un(this)}partial(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new _e({...this._def,shape:()=>n})}required(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ht;)i=i._def.innerType;n[r]=i}}),new _e({...this._def,shape:()=>n})}keyof(){return hl(ne.objectKeys(this.shape))}}_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:St.create(),typeName:F.ZodObject,...Q(t)});_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:St.create(),typeName:F.ZodObject,...Q(t)});_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:St.create(),typeName:F.ZodObject,...Q(t)});class er extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(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 a=i.map(c=>new Ve(c.ctx.common.issues));return P(n,{code:I.invalid_union,unionErrors:a}),B}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const l of r){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&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new Ve(l));return P(n,{code:I.invalid_union,unionErrors:c}),B}}get options(){return this._def.options}}er.create=(e,t)=>new er({options:e,typeName:F.ZodUnion,...Q(t)});const vt=e=>e instanceof rr?vt(e.schema):e instanceof ct?vt(e.innerType()):e instanceof sr?[e.value]:e instanceof Nt?e.options:e instanceof ir?ne.objectValues(e.enum):e instanceof or?vt(e._def.innerType):e instanceof Xn?[void 0]:e instanceof qn?[null]:e instanceof ht?[void 0,...vt(e.unwrap())]:e instanceof Lt?[null,...vt(e.unwrap())]:e instanceof eo||e instanceof cr?vt(e.unwrap()):e instanceof ar?vt(e._def.innerType):[];class ds extends J{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.object)return P(n,{code:I.invalid_type,expected:j.object,received:n.parsedType}),B;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);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}):(P(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const i of n){const a=vt(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new ds({typeName:F.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Q(r)})}}function mi(e,t){const n=wt(e),r=wt(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){const s=ne.objectKeys(t),i=ne.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=mi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=mi(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===j.date&&r===j.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class tr extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(i,a)=>{if(pi(i)||pi(a))return B;const c=mi(i.value,a.value);return c.valid?((hi(i)||hi(a))&&n.dirty(),{status:n.value,value:c.data}):(P(r,{code:I.invalid_intersection_types}),B)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}tr.create=(e,t,n)=>new tr({left:e,right:t,typeName:F.ZodIntersection,...Q(n)});class gt extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.array)return P(r,{code:I.invalid_type,expected:j.array,received:r.parsedType}),B;if(r.data.length<this._def.items.length)return P(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new mt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Le.mergeArray(n,a)):Le.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new gt({...this._def,rest:t})}}gt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gt({items:e,typeName:F.ZodTuple,rest:null,...Q(t)})};class nr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.object)return P(r,{code:I.invalid_type,expected:j.object,received:r.parsedType}),B;const s=[],i=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:i._parse(new mt(r,c,r.path,c)),value:a._parse(new mt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Le.mergeObjectAsync(n,s):Le.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof J?new nr({keyType:t,valueType:n,typeName:F.ZodRecord,...Q(r)}):new nr({keyType:ot.create(),valueType:t,typeName:F.ZodRecord,...Q(n)})}}class Xr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.map)return P(r,{code:I.invalid_type,expected:j.map,received:r.parsedType}),B;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new mt(r,c,r.path,[d,"key"])),value:i._parse(new mt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return B;(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 a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return B;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}Xr.create=(e,t,n)=>new Xr({valueType:t,keyType:e,typeName:F.ZodMap,...Q(n)});class qt extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.set)return P(r,{code:I.invalid_type,expected:j.set,received:r.parsedType}),B;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(P(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(P(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return B;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>i._parse(new mt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new qt({...this._def,minSize:{value:t,message:N.toString(n)}})}max(t,n){return new qt({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}qt.create=(e,t)=>new qt({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...Q(t)});class gn extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.function)return P(n,{code:I.invalid_type,expected:j.function,received:n.parsedType}),B;function r(c,l){return Kr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),wn].filter(d=>!!d),issueData:{code:I.invalid_arguments,argumentsError:l}})}function s(c,l){return Kr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),wn].filter(d=>!!d),issueData:{code:I.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof kn){const c=this;return Ue(async function(...l){const d=new Ve([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(h=>{throw d.addIssue(s(f,h)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new Ve([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new Ve([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new gn({...this._def,args:gt.create(t).rest(Vt.create())})}returns(t){return new gn({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new gn({args:t||gt.create([]).rest(Vt.create()),returns:n||Vt.create(),typeName:F.ZodFunction,...Q(r)})}}class rr extends J{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})}}rr.create=(e,t)=>new rr({getter:e,typeName:F.ZodLazy,...Q(t)});class sr extends J{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return P(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:t.data}}get value(){return this._def.value}}sr.create=(e,t)=>new sr({value:e,typeName:F.ZodLiteral,...Q(t)});function hl(e,t){return new Nt({values:e,typeName:F.ZodEnum,...Q(t)})}class Nt extends J{constructor(){super(...arguments),Bn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{expected:ne.joinValues(r),received:n.parsedType,code:I.invalid_type}),B}if(Yr(this,Bn)||dl(this,Bn,new Set(this._def.values)),!Yr(this,Bn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{received:n.data,code:I.invalid_enum_value,options:r}),B}return Ue(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 Nt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Nt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Bn=new WeakMap;Nt.create=hl;class ir extends J{constructor(){super(...arguments),Gn.set(this,void 0)}_parse(t){const n=ne.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==j.string&&r.parsedType!==j.number){const s=ne.objectValues(n);return P(r,{expected:ne.joinValues(s),received:r.parsedType,code:I.invalid_type}),B}if(Yr(this,Gn)||dl(this,Gn,new Set(ne.getValidEnumValues(this._def.values))),!Yr(this,Gn).has(t.data)){const s=ne.objectValues(n);return P(r,{received:r.data,code:I.invalid_enum_value,options:s}),B}return Ue(t.data)}get enum(){return this._def.values}}Gn=new WeakMap;ir.create=(e,t)=>new ir({values:e,typeName:F.ZodNativeEnum,...Q(t)});class kn extends J{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.promise&&n.common.async===!1)return P(n,{code:I.invalid_type,expected:j.promise,received:n.parsedType}),B;const r=n.parsedType===j.promise?n.data:Promise.resolve(n.data);return Ue(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}kn.create=(e,t)=>new kn({type:e,typeName:F.ZodPromise,...Q(t)});class ct extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:a=>{P(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return B;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?B:l.status==="dirty"||n.value==="dirty"?hn(l.value):l});{if(n.value==="aborted")return B;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?B:c.status==="dirty"||n.value==="dirty"?hn(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,i);if(r.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(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?B:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?B:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jt(a))return a;const c=s.transform(a.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:r.data,path:r.path,parent:r}).then(a=>Jt(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);ne.assertNever(s)}}ct.create=(e,t,n)=>new ct({schema:e,typeName:F.ZodEffects,effect:t,...Q(n)});ct.createWithPreprocess=(e,t,n)=>new ct({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...Q(n)});class ht extends J{_parse(t){return this._getType(t)===j.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:F.ZodOptional,...Q(t)});class Lt extends J{_parse(t){return this._getType(t)===j.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Lt.create=(e,t)=>new Lt({innerType:e,typeName:F.ZodNullable,...Q(t)});class or extends J{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===j.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}or.create=(e,t)=>new or({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Q(t)});class ar extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Qn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ar.create=(e,t)=>new ar({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Q(t)});class qr extends J{_parse(t){if(this._getType(t)!==j.nan){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.nan,received:r.parsedType}),B}return{status:"valid",value:t.data}}}qr.create=e=>new qr({typeName:F.ZodNaN,...Q(e)});const Ef=Symbol("zod_brand");class eo extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class _r extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?B:i.status==="dirty"?(n.dirty(),hn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?B:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new _r({in:t,out:n,typeName:F.ZodPipeline})}}class cr extends J{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Jt(s)&&(s.value=Object.freeze(s.value)),s);return Qn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}cr.create=(e,t)=>new cr({innerType:e,typeName:F.ZodReadonly,...Q(t)});function la(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ml(e,t={},n){return e?Sn.create().superRefine((r,s)=>{var i,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=la(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;s.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=la(t,r),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...l,fatal:d})}}):Sn.create()}const If={object:_e.lazycreate};var F;(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"})(F||(F={}));const xf=(e,t={message:`Input not instance of ${e.name}`})=>ml(n=>n instanceof e,t),gl=ot.create,yl=Mt.create,Tf=qr.create,Cf=Dt.create,_l=Jn.create,Af=Xt.create,Of=Qr.create,Pf=Xn.create,jf=qn.create,Mf=Sn.create,Df=Vt.create,Nf=St.create,Lf=Jr.create,$f=at.create,Uf=_e.create,Ff=_e.strictCreate,Bf=er.create,Gf=ds.create,Hf=tr.create,Wf=gt.create,zf=nr.create,Zf=Xr.create,Vf=qt.create,Kf=gn.create,Yf=rr.create,Qf=sr.create,Jf=Nt.create,Xf=ir.create,qf=kn.create,da=ct.create,ep=ht.create,tp=Lt.create,np=ct.createWithPreprocess,rp=_r.create,sp=()=>gl().optional(),ip=()=>yl().optional(),op=()=>_l().optional(),ap={string:e=>ot.create({...e,coerce:!0}),number:e=>Mt.create({...e,coerce:!0}),boolean:e=>Jn.create({...e,coerce:!0}),bigint:e=>Dt.create({...e,coerce:!0}),date:e=>Xt.create({...e,coerce:!0})},cp=B;var o=Object.freeze({__proto__:null,defaultErrorMap:wn,setErrorMap:tf,getErrorMap:Vr,makeIssue:Kr,EMPTY_PATH:nf,addIssueToContext:P,ParseStatus:Le,INVALID:B,DIRTY:hn,OK:Ue,isAborted:pi,isDirty:hi,isValid:Jt,isAsync:Qn,get util(){return ne},get objectUtil(){return fi},ZodParsedType:j,getParsedType:wt,ZodType:J,datetimeRegex:pl,ZodString:ot,ZodNumber:Mt,ZodBigInt:Dt,ZodBoolean:Jn,ZodDate:Xt,ZodSymbol:Qr,ZodUndefined:Xn,ZodNull:qn,ZodAny:Sn,ZodUnknown:Vt,ZodNever:St,ZodVoid:Jr,ZodArray:at,ZodObject:_e,ZodUnion:er,ZodDiscriminatedUnion:ds,ZodIntersection:tr,ZodTuple:gt,ZodRecord:nr,ZodMap:Xr,ZodSet:qt,ZodFunction:gn,ZodLazy:rr,ZodLiteral:sr,ZodEnum:Nt,ZodNativeEnum:ir,ZodPromise:kn,ZodEffects:ct,ZodTransformer:ct,ZodOptional:ht,ZodNullable:Lt,ZodDefault:or,ZodCatch:ar,ZodNaN:qr,BRAND:Ef,ZodBranded:eo,ZodPipeline:_r,ZodReadonly:cr,custom:ml,Schema:J,ZodSchema:J,late:If,get ZodFirstPartyTypeKind(){return F},coerce:ap,any:Mf,array:$f,bigint:Cf,boolean:_l,date:Af,discriminatedUnion:Gf,effect:da,enum:Jf,function:Kf,instanceof:xf,intersection:Hf,lazy:Yf,literal:Qf,map:Zf,nan:Tf,nativeEnum:Xf,never:Nf,null:jf,nullable:tp,number:yl,object:Uf,oboolean:op,onumber:ip,optional:ep,ostring:sp,pipeline:rp,preprocess:np,promise:qf,record:zf,set:Vf,strictObject:Ff,string:gl,symbol:Of,transformer:da,tuple:Wf,undefined:Pf,union:Bf,unknown:Df,void:Lf,NEVER:cp,ZodIssueCode:I,quotelessJson:ef,ZodError:Ve});const ua=o.enum(["app_start","sign_in","window_focus","surface_open"]),vl=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),lp=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:vl.nullable()}).passthrough(),dp=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),up=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),zS=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(lp)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:dp.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:up}).passthrough(),fp=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.enum(["dialog","settings"]),current:o.boolean()}).passthrough(),ZS=o.object({endpoint:vl.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:fp.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough()}).passthrough(),pp=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),fa=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:pp,id:o.string().optional()}).passthrough(),pa=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),VS=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(fa)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(fa),directions:o.object({send:pa,receive:pa}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough();function KS(e,t){if(!e||!t||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function YS(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const hp=8,gi=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh"],mp=6*1024,gp=512;function es(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const i of n){if(s.length===gp)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(r+c>mp)break;e.append("order_ids",i),s.push(i),r+=c}return s}function yp(e,t,n){return es(new URLSearchParams(n),t,e)}const k=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Cr=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Ar=o.string().min(1).max(32768),_p=/^[a-f0-9]{12}$/,L=o.string().regex(_p),Ds=o.string().regex(/^[a-f0-9]{12}$/),Ns=o.string().min(1).max(128),vp=o.string().min(1).max(4096),Ls=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Or=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),ha=o.string().regex(/^[a-f0-9]{32}$/),bp=/^(\/|[A-Za-z]:[\\/])/,$s=o.string().min(1).max(4096).regex(bp),ma=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),ga=o.string().min(1).max(512).nullish(),ln=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),ya=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Mn=o.string().regex(/^la_[0-9a-f]{16}$/),Dn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),_a=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),wp=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),va=2e5,ba=8,Sp=256,kp=100,wa=16,Rp=256,Ep=100,Ip=200,xp=1e6,Tp=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Oe=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Pr=o.object({kind:o.enum(["agent","team"]),name:Oe}).strict(),bl=o.enum(["claude","codex","omp"]),Cp=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),Sa={sources:o.array(bl).max(3).optional(),sessionIds:Cp.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},Us=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable()}).strict(),ka=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),Ra=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Oe.optional(),members:o.array(o.object({role:Oe,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:Tp.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Ap=o.record(o.array(o.string().max(1024)).max(100)),Ea=o.enum(["minutes","hours","days"]);function Op(e){return!/^\.+$/.test(e)}const QS=e=>Hr.safeParse(e).success,Hr=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Op),Ia=o.enum(["str","int","float","bool","list","dict"]),xa=o.string().max(16384),Pp=2e3,Ta=o.string().min(1).max(Pp),Ca=o.string().min(1).max(64),jp=o.string().min(1).max(64),Mp=o.string().min(1).max(64),Aa=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),Dp=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),yi=128,Oa=2e3,Pa=8e3,ja=64,Ma=64,us=e=>[...e].length,_i=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,Np=e=>e===9||e===10||e===11||e===12||e===13||e===133,Lp=e=>e<=31||e>=127&&e<=159,$p=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),Up=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,jr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},wl=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&_i(t[n].codePointAt(0)??0);)n++;for(;r>n&&_i(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Fp=e=>{let t="",n=!1;for(const r of e){if(_i(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Bp(e){const t=wl(e);if(!t)return"must not be empty";if(us(t)>yi)return`must be at most ${yi} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(jr(t,Up))return"must not contain Unicode bidirectional override characters";if(jr(t,Np))return"must not contain whitespace";if(jr(t,Lp))return"must not contain control characters";if(jr(t,$p))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 JS(e){return Fp(wl(e).normalize("NFKC").toLowerCase())}function Gp(e){return e.trim()?us(e)>Oa?`must be at most ${Oa} characters`:null:"must not be empty"}function Hp(e){return e.trim()?us(e)>Pa?`must be at most ${Pa} characters`:null:"must not be empty"}function Wp(e){if(e.length>Ma)return`must hold at most ${Ma} items`;for(const t of e)if(!t.trim()||us(t)>ja)return`must hold items of 1 to ${ja} characters`;return null}const zp=e=>Bp(e)===null,Zp=o.string().refine(zp,{message:"That is not a name the hub can publish."}),Vp=o.string().refine(e=>Hp(e)===null,{message:"That instruction body cannot be published."}),Kp=o.string().refine(e=>Gp(e)===null,{message:"That description cannot be published."}),Yp=o.array(o.string()).refine(e=>Wp(e)===null,{message:"That tool list cannot be published."}),Fs={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},Da=o.object({name:Zp,description:Kp,instructions:Vp,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:Yp,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),Qp=o.enum(["team","agent"]),Jp=o.string().min(1).max(64),Xp=o.string().min(1).max(256),Sl=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Bs=o.string().regex(Sl,{message:"Letters, digits, dot, underscore and dash; no spaces."}),qp=["planning","active","qa","validation","done","paused","archived"],Na=o.enum(qp),Mr=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),La=o.array(o.string().min(1).max(24)).max(8),Tt=o.string().min(1).max(64),eh=1e3,$a=240,Ua=80,th=256,nh=100,rh=200,sh=/^[a-z0-9][a-z0-9_-]{0,23}$/;function XS(e){return e?Sl.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 qS(e){return sh.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Dr=o.enum(["agent","team","skill"]),Fa=o.enum(gi),ih=o.object({visible:o.array(Fa).max(gi.length),more:o.array(Fa).max(gi.length)}).strict(),oh=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Oe}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:bl,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...Sa}).strict(),o.object({op:o.literal("imports.start"),...Sa}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Oe,requestId:te,fields:ka,expectedDefinitionRevision:ga.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Oe,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Oe,requestId:te,fields:ka.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:k,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:k.nullable(),localAlias:Oe,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:k,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:k.nullable(),localAlias:Oe}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Oe,localAlias:Oe,visibility:o.enum(["public","org"]),tenantId:k.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Dr.optional(),name:Oe.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,previewReceipt:o.string().min(1).max(4096).optional(),confirmApply:o.literal(!0).optional(),linkId:o.string().min(1).max(256).optional(),direction:o.literal("pull").optional(),kind:Dr.optional(),name:Oe.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Dr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Dr.optional(),name:Oe.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Oe}).strict(),o.object({op:o.literal("teams.effective"),name:Oe}).strict(),o.object({op:o.literal("teams.update"),name:Oe,requestId:te,fields:Ra,expectedDefinitionRevision:ga.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:Ra.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:Qp.optional(),scope_name:Jp.optional(),cursor:Xp.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(Sp),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Pr.optional(),purpose:o.literal("agents-config").optional(),model:Us.optional(),draftId:L.optional(),peer:ln.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Pr.optional(),model:Us.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Pr.optional(),model:Us.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:k.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(k).max(wa).optional(),limit:o.number().int().min(1).max(wa).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(Rp),limit:o.number().int().min(1).max(Ip).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:k.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(va),images:o.array(_a).max(ba).optional(),files:o.array(wp).max(hp).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(va).optional(),images:o.array(_a).max(ba).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:k.optional(),requestId:k.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:k.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(ma),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Ds,anchor:Ns}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Ds,anchor:Ns}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Ds,anchor:Ns,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:Hr,value:xa,type:Ia}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:Hr,value:xa,type:Ia}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:Hr}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:k}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:k}).strict(),o.object({op:o.literal("agent.publish"),agentId:k,document:Da.optional(),...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:k,hubAgentId:k,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:Da.optional(),...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:k,...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:k,tenantId:k.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(yi)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:k,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:k.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:k}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:k,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:k,schedule:Aa.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:Ea})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:k}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:k,schedule:Aa.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:Ea.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:k}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:k,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:k,systemPrompt:o.string().max(xp)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:k}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:k}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:k,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:k.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:k.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:vp.optional(),name:k.optional()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Cr.optional(),value:Ar.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(ma).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Pr.optional(),message:Ta,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:Ca,message:Ta.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:Ca}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:jp}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:Mp}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Ls.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Or).optional(),url:o.string().max(4096).optional(),headers:o.record(Or).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:ha.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:$s.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:$s.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Ls.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Or).optional(),url:o.string().max(4096).optional(),headers:o.record(Or).optional(),confirmed:o.boolean().optional(),operation_id:ha.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:$s.optional(),name:Ls,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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","org_skills.list","org_skill.get","signup.resend"]),request_id:te.optional(),tenant_id:k.optional(),account_id:k.optional(),agent_id:k.optional(),comment_id:k.optional(),team_id:k.optional(),skill_id:k.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:k}).strict(),o.object({op:o.literal("auth.status"),id:k}).strict(),o.object({op:o.literal("auth.input"),id:k,promptId:k,value:Ar}).strict(),o.object({op:o.literal("auth.cancel"),id:k}).strict(),o.object({op:o.literal("auth.key"),provider:k,value:Ar}).strict(),o.object({op:o.literal("auth.logout"),provider:k}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:ua}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:k,tenant_id:k,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:k.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:k,tenant_id:k.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:k.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:k,tenant_id:k.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:k.optional(),account_id:k.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(64).optional(),before:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:k,tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:k.optional(),tenant_id:k.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:k,kind:o.enum(["human","agent"]),endpoint_id:k.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:k.optional(),tenant_id:k.optional(),conversation_id:k,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),members:o.array(o.object({account_id:k,kind:o.enum(["human","agent"]),endpoint_id:k.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:k.optional(),tenant_id:k.optional(),conversation_id:k,account_id:k}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:k.optional(),conversation_id:k,account_id:k,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:k,tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:k,message_id:k,tenant_id:k.optional(),emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),client_ref:k,body:o.string().min(1),agent_label:o.string().min(1).max(64).optional(),thread_root_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:k,message_id:k,tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:k}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:ua.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Cr,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Ap.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Cr}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:Dp}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Cr,value:Ar}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:ln,role:o.enum(["read","drive","admin"]),deviceId:ln.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:ln,deviceId:ln,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),ln]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:ya}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:ya}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Tt}).strict(),o.object({op:o.literal("projects.create"),name:Bs,description:o.string().max($a).optional(),status:Na.optional(),tags:La.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Tt,fields:o.object({name:Bs.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max($a).optional(),status:Na.optional(),progress:o.string().max(eh).optional(),tags:La.optional(),start_date:Mr.optional(),target_date:Mr.optional(),completed_at:Mr.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Tt,confirmed_name:Bs}).strict(),o.object({op:o.literal("projects.link"),key:Tt,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Tt,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Tt,name:o.string().min(1).max(Ua),targetDate:Mr.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Tt,name:o.string().min(1).max(Ua)}).strict(),o.object({op:o.literal("projects.request_update"),key:Tt}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(th),limit:o.number().int().min(1).max(rh).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Mn}).strict(),o.object({op:o.literal("library.update"),id:Mn,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:Dn,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:Dn}).strict(),o.object({op:o.literal("library.tags.merge"),id:Dn,into:Dn}).strict(),o.object({op:o.literal("library.tags.assign"),id:Mn,tags:o.array(Dn).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Mn,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Mn}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:ih}).strict()]);oh.superRefine((e,t)=>{if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:o.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:o.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.linkId!==void 0,r=e.kind!==void 0||e.name!==void 0;if(n&&r||e.op!=="hub.check"&&!n&&(!e.kind||!e.name)||e.op==="hub.retry"&&n&&!e.direction||e.direction==="push"&&!n){t.addIssue({code:o.ZodIssueCode.custom,message:"A hub action requires one unambiguous selector and an explicit retry direction",path:["linkId"]});return}}if(e.op==="hub.apply"&&(e.previewReceipt!==void 0||e.confirmApply!==void 0)&&(!e.linkId||e.dryRun||!e.previewReceipt||e.confirmApply!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"A viewed incoming application requires its scoped preview receipt and confirmation",path:["previewReceipt"]});return}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.linkId!==void 0||e.previewReceipt!==void 0||e.confirmApply!==void 0||e.prefer!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, with no link, preview or preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:o.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Je={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},ah={runtimeUnreachable:"runtime_unreachable"},fs="runtime_busy",kl="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const ek="aside_adopt_refused",ch=["session_closed","open_tool_batch","turn_running"];function tk(e){if(typeof e!="object"||e===null)return;const t=e.reason;return ch.find(n=>n===t)}const to={[Je.noCredential]:"This app is not paired with the running Local Operator server, so this control is unavailable.",[Je.refused]:"This app's credential for the running Local Operator server was refused, so this control is unavailable.",[Je.planeClosed]:"The running Local Operator server does not accept this app's desktop controls.",[Je.transportFailed]:"The Local Operator server did not answer this request."},vi={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 ps(e){return e!==void 0&&Object.values(Je).includes(e)}function lh(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Je.refused;if(t===503)return Je.planeClosed}}const nk=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),rk=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),dh=88e4,uh=11e5,fh=2e4,ph=9e4,hh=new Set(["analytics.get","analytics.models","sessions.report"]),mh=new Set(["usage.get"]),gh=new Set(["networks.list","peers.list"]),yh=new Set([...hh,...mh,...gh]),_h=90,vh=30,bh=300,wh=10,Rl=15,Sh=1e4;function kh(e){const n=e.to==="local"||e.keep?bh:vh,r=Math.max(0,e.waitS??0);return(_h+n+wh+Rl)*1e3+r*1e3}const Rh=18e4,Eh=Rh+15e3,Ih=120,xh=135e3,Th=93e4,El=(Ih+30+Rl)*1e3,Ch=6e4,Ah=5*El,Oh=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Ph(e){switch(e){case"hub.apply":case"hub.retry":case"hub.push":case"hub.skillPublish":case"hub.skillPull":case"hub.skillSubscribe":case"hub.skillUnpull":return El;case"hub.check":return Ch;case"hub.applyAll":return Ah;default:return null}}function jh(e){if(typeof e!="string"&&e.op==="sessions.transfer")return kh(e)+Sh;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve")return Eh;if(t==="tunnel.setup.run")return Th;if(t==="tunnel.setup.plan")return xh;const n=Ph(t);return n!==null?n:yh.has(t)?ph:fh}const Mh=5e3;function Il(e){return jh(e)+Mh}const no="deadline_exceeded",xl="foreground_required",Tl="View these completions in the foreground before marking them read.",Dh=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","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","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Nh=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Lh(e,t){const n=Math.round(t/1e3),r=no;return e==="sessions.transfer"?{code:r,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.`}:e==="approvals.approve"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:Oh.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Dh.has(e)?{code:r,message:Nh.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:r,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 sk=dh,ik=uh;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function $h(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Ba(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 Gs(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Hs(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 Ga(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Ha(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function Nr(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Uh(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",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"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};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"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Ga(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Ga(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};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,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmApply?{confirm_apply:!0}:{},...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};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.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,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,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};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"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??kp)});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,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};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":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),es(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),es(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{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??Ep)});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??[],...e.files?.length?{files:e.files}:{},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 e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{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"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};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"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};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":{Hs(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??{},...Gs(e)}}}case"agent.republish":{Hs(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??{},...Gs(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Hs(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Gs(e)}}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,...$h(e),message:e.message,...Ba(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Ba(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};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":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,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"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${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":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,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,entry_id:e.entryId,auto_tag:e.autoTag}};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"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};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"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Nr(e.tenant_id)}`,method:"GET"};case"agent_messages.settings.put":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},...e.consent_version===void 0?{}:{consent_version:e.consent_version},...e.consented_via===void 0?{}:{consented_via:e.consented_via},...e.label===void 0?{}:{label:e.label},state:e.state}};case"agent_messages.allowlist.get":return{path:`/v1/desktop/team-bridge/allowlist${Nr(e.tenant_id)}`,method:"GET"};case"agent_messages.allowlist.put":return{path:"/v1/desktop/team-bridge/allowlist",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},entries:e.entries}};case"team_bridge.conversations.list":{const t=new URLSearchParams;return e.scope==="account"&&t.set("scope","account"),e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.before&&t.set("before",e.before),{path:`/v1/desktop/team-bridge/conversations${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.conversations.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Nr(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Ha(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Ha(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,consent_version:e.consent_version}};case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:e.tenant_id?{tenant_id:e.tenant_id}:{}}:{path:`${t}${Nr(e.tenant_id)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.messages.replies":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq));const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}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"tts.paths":return{path:"/v1/tts/paths",method:"GET"};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"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}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,...e.force_done===!0?{force_done:!0}:{}}};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"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??nh)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}}}}const ok=64,ak=64*1024*1024,ck="superseded_completion_token",lk="store_busy",Fh="session_is_remote",Bh="owner_build_behind";function dk(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function mn(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=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 Gh(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const uk=e=>typeof e?.goal_status=="string",fk=e=>(e?.goal??"").trim().length>0;function Hh(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 Zn={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."},Wa={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},Wh={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},zh={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},Zh={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},Vh={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function za(e){return e?e===Zn.notPaired?zh:e===Zn.serverDown?Wh:e===Zn.frameBudget?Vh:Wa:Wa}const Za=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(h=>h(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,s,c);return c},Kh=e=>e?Za(e):Za,Yh=e=>e;function Qh(e,t=Yh){const n=aa.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return aa.useDebugValue(n),n}const Va=e=>{const t=Kh(e),n=r=>Qh(t,r);return Object.assign(n,t),n},vr=e=>e?Va(e):Va;function Cl(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(s))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const bi=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return bi(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return bi(r)(n)}}}},Jh=(e,t)=>(n,r,s)=>{let i={storage:Cl(()=>localStorage),partialize:m=>m,version:0,merge:(m,y)=>({...y,...m}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...m)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...m)},r,s);const u=()=>{const m=i.partialize({...r()});return d.setItem(i.name,{state:m,version:i.version})},f=s.setState;s.setState=(m,y)=>{f(m,y),u()};const p=e((...m)=>{n(...m),u()},r,s);s.getInitialState=()=>p;let h;const g=()=>{var m,y;if(!d)return;a=!1,c.forEach(b=>{var R;return b((R=r())!=null?R:p)});const _=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(m=r())!=null?m:p))||void 0;return bi(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate){const R=i.migrate(b.state,b.version);return R instanceof Promise?R.then(M=>[!0,M]):[!0,R]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,b.state];return[!1,void 0]}).then(b=>{var R;const[M,G]=b;if(h=i.merge(G,(R=r())!=null?R:p),n(h,!0),M)return u()}).then(()=>{_?.(h,void 0),h=r(),a=!0,l.forEach(b=>b(h))}).catch(b=>{_?.(void 0,b)})};return s.persist={setOptions:m=>{i={...i,...m},m.storage&&(d=m.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>a,onHydrate:m=>(c.add(m),()=>{c.delete(m)}),onFinishHydration:m=>(l.add(m),()=>{l.delete(m)})},i.skipHydration||g(),h||p},hs=Jh,Xh=(e,t)=>e!==null&&e.message===t.message&&e.removed===t.removed&&e.max_age_hours===t.max_age_hours&&e.in_progress===t.in_progress&&e.first_removal_at===t.first_removal_at&&e.freed_bytes_estimate===t.freed_bytes_estimate&&e.record===t.record;function qh(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,s)=>typeof r=="number"&&Number.isFinite(r)?r:s;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Al=vr()(hs(e=>({notice:null,receive:t=>e(n=>Xh(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Cl(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));async function Ol(e){if(window.api?.desktop)try{return await em(window.api.desktop.request(e),e)}catch(n){throw n instanceof ye?n:om(n)?new $t(Tl,xl):new ye(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 ye(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new ye(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function em(e,t){const n=Il(t);let r;return Promise.race([e,new Promise((s,i)=>{r=setTimeout(()=>{const a=Lh(t.op,n);i(new ye(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const tm="This server did not answer the request for its desktop controls.";class ye extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=i,this.detail=a}}class $t extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function ro(e,t){return e instanceof ye||e instanceof $t?ps(e.code)?to[e.code]:e.message:t}function nm(e,t,n,r){return typeof r=="string"?r:n===vi.noCredential?Je.noCredential:n===vi.transportFailed?Je.transportFailed:lh(Uh(e).path,t)}async function xe(e){const t=await Ol(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new ye(t.status,r??tm,void 0,nm(e,t.status,r,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,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&rm(n?.result),n?.result}function rm(e){if(typeof e!="object"||e===null)return;const t=qh(e.delegated_cleanup_notice);t&&Al.getState().receive(t)}async function sm(){try{await xe({op:"delegated_cleanup_notice.ack"})}catch{}}async function pk(){Al.getState().dismiss(),await sm()}function im(e){return e instanceof ye&&e.code===no}function hk(e){if(!(e instanceof ye))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Bh:e.code===Fh}function mk(e){return e instanceof $t&&e.code===xl}function om(e){return e instanceof Error&&e.message.includes(Tl)}async function gk(e){const t=await Ol(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function yk(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await xe({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function am(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),es(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=i=>{t({kind:"data",data:i.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Zn.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function _k(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=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}),s=r.headers.get("content-type")??"";if(!r.ok){let i="The media request failed.",a;if(s.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")i=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?i=d.text:typeof d.message=="string"&&d.message.trim()&&(i=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:i,code:a!==void 0&&ps(a)?a:i===vi.noCredential?Je.noCredential:void 0}}return s.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:s||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function vk(e){return e.kind==="error"?ps(e.code)?new $t(to[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const Nn=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function cm(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Nn(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Nn(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Nn(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const s=new Map;for(const a of r){const c=Nn(a);c!==null&&s.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=s.get(c);l&&(i.push(l),s.delete(c))}for(const a of r){const c=Nn(a);c!==null&&s.has(c)?(i.push(a),s.delete(c)):c===null&&i.push(a)}return i}const wi=e=>({revision:Ye(e),demand:e.orderDemand}),Kt=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Rn(e,t,n,r,s,i={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&s&&a.orderNeedsReconcile&&a.orderDemand===s.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},i.peer===!0)){const p=(a.orderRevision??0)+1,h=new Map;for(const g of a.records){const m=g.sourceEntryId??(g.kind==="tool"||g.kind==="supplement"?null:g.id);typeof m=="string"&&m.length>0&&m.length<=128&&h.set(m,p)}l={...l,...h.size>0?{journalBodyOwed:h}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,h,g)=>{if(!Kt(g))return;const m=d.get(p);m&&m.seq>=g||(d===u&&(d=new Map(d)),d.set(p,{entryId:h,seq:g}))};for(const[p,h]of Object.entries(t.journal_ordinals??{}))f(p,p,h);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function so(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const s=n,i=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===i&&(r=new Map(r)),r.set(a.id,c)))}),n===s&&r===i?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Pl(e,t){const n=new Set(e.map(i=>i.id));let r=!1,s;for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="user"&&a.provisional===!0){s=a;continue}!t(a)&&s&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:s.id},r=!0),s=e[i]}return r}function jl(e,t,n,r,s){const i=[],a=new Set;let c=e,l;for(;c!==void 0;){if(s.has(c.id)){l=s.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)s.set(d,l);return l}function Ml(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const i=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?s:void 0}}function ts(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=s.get(l);d?d.push(c):s.set(l,[c])});let i=t;for(const a of s.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function Dl(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return lm(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1;const i=t.map(h=>{let m=[r?.get(h.sourceEntryId??h.id),r?.get(h.id)].filter(b=>b!==void 0).sort((b,R)=>R.seq-b.seq)[0];if(h.journalGeneration===n&&Kt(h.journalSeq)&&(!m||h.journalSeq>m.seq)&&(m={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),!m||!n||!(h.kind==="user"&&(h.provisional===!0||h.local===!0))&&h.sourceEntryId===m.entryId&&h.journalSeq===m.seq&&h.journalGeneration===n)return h;s=!0;let _={...h,sourceEntryId:m.entryId,journalSeq:m.seq,journalGeneration:n};if(_.kind==="user"){const{provisional:b,local:R,...M}=_;_=M}return _});Pl(i,h=>h.journalGeneration===n&&Kt(h.journalSeq))&&(s=!0);const c=new Map,l=new Map(i.map(h=>[h.id,h])),d=Ml(l,h=>h!==void 0&&h.journalGeneration===n&&Kt(h.journalSeq)?h.journalSeq:void 0),u=h=>d(h)!==void 0,f=(h,g)=>{const m=d(h);if(h.kind==="user"&&h.provisional===!0&&m===void 0)return[1,0,0,0,g];const y=h.kind==="supplement"?h.anchor:h.kind==="tool"?e.journalCallOwners?.get(h.toolCallId)??e.argsByCall.get(h.toolCallId)?.anchorId:void 0,_=typeof y=="string"?d(l.get(y)):void 0,b=m===void 0?jl(h,l,u,d,c):void 0,R=_??m??b;return R===void 0?[1,0,0,0,g]:[0,R,_!==void 0?1:m!==void 0?0:2,m??Number.MAX_SAFE_INTEGER,g]},p=i.map((h,g)=>({record:h,index:g,rank:f(h,g)}));return p.sort((h,g)=>{for(let m=0;m<h.rank.length;m++){const y=h.rank[m]-g.rank[m];if(y)return y}return 0}),!s&&p.every((h,g)=>h.index===g)?ts(e,t):ts(e,p.map(h=>h.record))}function lm(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;for(const m of t){let _=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(b=>b!==void 0).sort((b,R)=>R.seq-b.seq)[0];m.journalGeneration===n&&Kt(m.journalSeq)&&(!_||m.journalSeq>_.seq)&&(_={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),_&&s.set(m.id,_)}const i=m=>m===void 0?void 0:s.get(m.id)??r?.get(m.sourceEntryId??m.id)??r?.get(m.id);let a=!1;const c=t.slice();Pl(c,m=>m.journalGeneration===n&&Kt(m.journalSeq))&&(a=!0);const d=new Map,u=new Map(c.map(m=>[m.id,m])),f=Ml(u,m=>i(m)?.seq),p=m=>f(m)!==void 0,h=(m,y)=>{const _=f(m);if(m.kind==="user"&&m.provisional===!0&&_===void 0)return[1,0,0,0,y];const b=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,R=typeof b=="string"?f(u.get(b)):void 0,M=_===void 0?jl(m,u,p,f,d):void 0,G=R??_??M;return G===void 0?[1,0,0,0,y]:[0,G,R!==void 0?1:_!==void 0?0:2,_??Number.MAX_SAFE_INTEGER,y]},g=c.map((m,y)=>({record:m,index:y,rank:h(m,y)}));return g.sort((m,y)=>{for(let _=0;_<m.rank.length;_++){const b=m.rank[_]-y.rank[_];if(b)return b}return 0}),!a&&g.every((m,y)=>m.index===y)?ts(e,t):ts(e,g.map(m=>m.record))}function ut(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!Kt(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...io(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const i=r[s];typeof i=="string"&&e.journalSourceVoid.has(i)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function io(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s=="string"&&s.length>0&&s.length<=128&&t.add(s)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function Nl(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Ye=e=>e.orderRevision??0;async function dm(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?io(c):l==="lookup"?Nl(c):ut(c);let s=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=wi(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=yp(r(c,f).filter(y=>!n(f).has(y)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),h=await e.read(p,f);if(!e.isCurrent()||Ye(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(h,d,l),!e.isCurrent())return{kind:"stale"};const g=e.getTranscript(),m=e.page(h);if(m.journal_order_state==="ready"&&m.journal_generation===g.journalGeneration){m.journal_generation!==s&&(t.clear(),s=m.journal_generation);for(const b of p)n(f).add(b);if(g.orderNeedsReconcile){if(g.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const b=(m.source_retry_ids??[]).filter(R=>typeof R=="string"&&R.length>0&&R.length<=128);if(b.length>0&&p.length>1&&a===0){a++;for(const R of b)n("payload").delete(R);continue}}const y=e.sweep?.(g,n);if(y?.kind==="none")return{kind:"complete",transcript:g};const _=y?.kind??"authority";if(r(g,_).some(b=>!n(_).has(b)))continue;return{kind:"complete",transcript:g}}if(!g.orderNeedsReconcile||g.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function rt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const s=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof s=="string"&&s?s:e.id}function Ws(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Ka(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function bk(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=Ws(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Ka(i.worked_seconds),failed:Ws(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:Ws(i.cross_session_action_count),crossSessionWorkedSeconds:Ka(i.cross_session_worked_seconds)};n.set(i.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const i of e.entries)r.add(rt(i));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?rt(s):null}}}function um(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(i=>i.opening_user_id===n.id))return null;const s=Math.round((n.ts??0)*1e3);return s>0?{id:n.id,tsMs:s}:null}function fm(e,t,n){const r=um(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const i=Math.round((s[s.length-1].ts??0)*1e3);if(!(i>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<i)))return!1;return!0}const oo=new Set,en="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Ll=new RegExp(`[${en}]`),wk=new RegExp(`[${en}]+`),Sk=new RegExp(`[${en}]+`,"g"),pm=new RegExp(`^[${en}]+|[${en}]+$`,"g"),hm=new RegExp(`^[${en}]+`),kk=new RegExp(`[^${en}]`);function Ot(e){return e.replace(pm,"")}function lr(e){return e.replace(hm,"")}function mm(e,t){return t===0||Ll.test(e[t-1])}function $l(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&mm(e,n)&&t.push(n);return t}function ao(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
1
|
+
import{t as ae}from"./messages-Bswe4yCX.js";import{b as aa,r as v,j as Xu,D as qu}from"./index-DXk6NfLu.js";var ne;(function(e){e.assertEqual=s=>s;function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),a={};for(const c of i)a[c]=s[c];return e.objectValues(a)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},e.find=(s,i)=>{for(const a of s)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var fi;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(fi||(fi={}));const j=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wt=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:e===null?j.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?j.promise:typeof Map<"u"&&e instanceof Map?j.map:typeof Set<"u"&&e instanceof Set?j.set:typeof Date<"u"&&e instanceof Date?j.date:j.object;default:return j.unknown}},I=ne.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"]),ef=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ve extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let c=r,l=0;for(;l<a.path.length;){const d=a.path[l];l===a.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(a))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return s(this),r}static assert(t){if(!(t instanceof Ve))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Ve.create=e=>new Ve(e);const wn=(e,t)=>{let n;switch(e.code){case I.invalid_type:e.received===j.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,ne.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${ne.joinValues(e.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ne.joinValues(e.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${ne.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.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}"`:ne.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case I.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 I.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 I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=t.defaultError,ne.assertNever(e)}return{message:n}};let ll=wn;function tf(e){ll=e}function Vr(){return ll}const Kr=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="";const l=r.filter(d=>!!d).slice().reverse();for(const d of l)c=d(a,{data:t,defaultError:c}).message;return{...s,path:i,message:c}},nf=[];function P(e,t){const n=Vr(),r=Kr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===wn?void 0:wn].filter(s=>!!s)});e.common.issues.push(r)}class Le{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return B;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return Le.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return B;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const B=Object.freeze({status:"aborted"}),hn=e=>({status:"dirty",value:e}),Ue=e=>({status:"valid",value:e}),pi=e=>e.status==="aborted",hi=e=>e.status==="dirty",Jt=e=>e.status==="valid",Qn=e=>typeof Promise<"u"&&e instanceof Promise;function Yr(e,t,n,r){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 dl(e,t,n,r,s){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 N;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(N||(N={}));var Bn,Gn;class mt{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}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 ca=(e,t)=>{if(Jt(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 Ve(e.common.issues);return this._error=n,this._error}}};function Q(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,c)=>{var l,d;const{message:u}=e;return a.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??r)!==null&&l!==void 0?l:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:s}}class J{get description(){return this._def.description}_getType(t){return wt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Le,ctx:{common:t.parent.common,data:t.data,parsedType:wt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Qn(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 r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const s={common:{issues:[],async:(r=n?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},i=this._parseSync({data:t,path:s.path,parent:s});return ca(s,i)}"~validate"(t){var n,r;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:s});return Jt(i)?{value:i.value}:{issues:s.common.issues}}catch(i){!((r=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(i=>Jt(i)?{value:i.value}:{issues:s.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:wt(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(Qn(s)?s:Promise.resolve(s));return ca(r,i)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=t(s),c=()=>i.addIssue({code:I.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new ct({schema:this,typeName:F.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 ht.create(this,this._def)}nullable(){return Lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return at.create(this)}promise(){return kn.create(this,this._def)}or(t){return er.create([this,t],this._def)}and(t){return tr.create(this,t,this._def)}transform(t){return new ct({...Q(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new or({...Q(this._def),innerType:this,defaultValue:n,typeName:F.ZodDefault})}brand(){return new eo({typeName:F.ZodBranded,type:this,...Q(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new ar({...Q(this._def),innerType:this,catchValue:n,typeName:F.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return _r.create(this,t)}readonly(){return cr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const rf=/^c[^\s-]{8,}$/i,sf=/^[0-9a-z]+$/,of=/^[0-9A-HJKMNP-TV-Z]{26}$/i,af=/^[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,cf=/^[a-z0-9_-]{21}$/i,lf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,df=/^[-+]?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)?)??$/,uf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ff="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ms;const pf=/^(?:(?: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])$/,hf=/^(?:(?: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])$/,mf=/^(([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]))$/,gf=/^(([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])$/,yf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_f=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ul="((\\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])))",vf=new RegExp(`^${ul}$`);function fl(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 bf(e){return new RegExp(`^${fl(e)}$`)}function pl(e){let t=`${ul}T${fl(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 wf(e,t){return!!((t==="v4"||!t)&&pf.test(e)||(t==="v6"||!t)&&mf.test(e))}function Sf(e,t){if(!lf.test(e))return!1;try{const[n]=e.split("."),r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function kf(e,t){return!!((t==="v4"||!t)&&hf.test(e)||(t==="v6"||!t)&&gf.test(e))}class ot extends J{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==j.string){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.string,received:i.parsedType}),B}const r=new Le;let s;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,c=t.data.length<i.value;(a||c)&&(s=this._getOrReturnCtx(t,s),a?P(s,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&P(s,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")uf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"email",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ms||(Ms=new RegExp(ff,"u")),Ms.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"emoji",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")af.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"uuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")cf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"nanoid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")rf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cuid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")sf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cuid2",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")of.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"ulid",code:I.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),P(s,{validation:"url",code:I.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"regex",code:I.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.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)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?pl(i).test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?vf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?bf(i).test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{code:I.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?df.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"duration",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?wf(t.data,i.version)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"ip",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Sf(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"jwt",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?kf(t.data,i.version)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"cidr",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?yf.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"base64",code:I.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?_f.test(t.data)||(s=this._getOrReturnCtx(t,s),P(s,{validation:"base64url",code:I.invalid_string,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:I.invalid_string,...N.errToObj(r)})}_addCheck(t){return new ot({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...N.errToObj(t)})}url(t){return this._addCheck({kind:"url",...N.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...N.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...N.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...N.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...N.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...N.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...N.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...N.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...N.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...N.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...N.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...N.errToObj(t)})}datetime(t){var n,r;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:(r=t?.local)!==null&&r!==void 0?r:!1,...N.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,...N.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...N.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...N.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...N.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...N.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...N.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...N.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...N.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...N.errToObj(n)})}nonempty(t){return this.min(1,N.errToObj(t))}trim(){return new ot({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ot({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ot({...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}}ot.create=e=>{var t;return new ot({checks:[],typeName:F.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Q(e)})};function Rf(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(e.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class Mt extends J{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)!==j.number){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.number,received:i.parsedType}),B}let r;const s=new Le;for(const i of this._def.checks)i.kind==="int"?ne.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Rf(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_finite,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new Mt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new Mt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:N.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:N.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&ne.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Mt.create=e=>new Mt({checks:[],typeName:F.ZodNumber,coerce:e?.coerce||!1,...Q(e)});class Dt extends J{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)!==j.bigint)return this._getInvalidInput(t);let r;const s=new Le;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),P(r,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return P(n,{code:I.invalid_type,expected:j.bigint,received:n.parsedType}),B}gte(t,n){return this.setLimit("min",t,!0,N.toString(n))}gt(t,n){return this.setLimit("min",t,!1,N.toString(n))}lte(t,n){return this.setLimit("max",t,!0,N.toString(n))}lt(t,n){return this.setLimit("max",t,!1,N.toString(n))}setLimit(t,n,r,s){return new Dt({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(s)}]})}_addCheck(t){return new Dt({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:N.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}}Dt.create=e=>{var t;return new Dt({checks:[],typeName:F.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...Q(e)})};class Jn extends J{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==j.boolean){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.boolean,received:r.parsedType}),B}return Ue(t.data)}}Jn.create=e=>new Jn({typeName:F.ZodBoolean,coerce:e?.coerce||!1,...Q(e)});class Xt extends J{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==j.date){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_type,expected:j.date,received:i.parsedType}),B}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return P(i,{code:I.invalid_date}),B}const r=new Le;let s;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),P(s,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):ne.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Xt({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:N.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:N.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}}Xt.create=e=>new Xt({checks:[],coerce:e?.coerce||!1,typeName:F.ZodDate,...Q(e)});class Qr extends J{_parse(t){if(this._getType(t)!==j.symbol){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.symbol,received:r.parsedType}),B}return Ue(t.data)}}Qr.create=e=>new Qr({typeName:F.ZodSymbol,...Q(e)});class Xn extends J{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.undefined,received:r.parsedType}),B}return Ue(t.data)}}Xn.create=e=>new Xn({typeName:F.ZodUndefined,...Q(e)});class qn extends J{_parse(t){if(this._getType(t)!==j.null){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.null,received:r.parsedType}),B}return Ue(t.data)}}qn.create=e=>new qn({typeName:F.ZodNull,...Q(e)});class Sn extends J{constructor(){super(...arguments),this._any=!0}_parse(t){return Ue(t.data)}}Sn.create=e=>new Sn({typeName:F.ZodAny,...Q(e)});class Vt extends J{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ue(t.data)}}Vt.create=e=>new Vt({typeName:F.ZodUnknown,...Q(e)});class St extends J{_parse(t){const n=this._getOrReturnCtx(t);return P(n,{code:I.invalid_type,expected:j.never,received:n.parsedType}),B}}St.create=e=>new St({typeName:F.ZodNever,...Q(e)});class Jr extends J{_parse(t){if(this._getType(t)!==j.undefined){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.void,received:r.parsedType}),B}return Ue(t.data)}}Jr.create=e=>new Jr({typeName:F.ZodVoid,...Q(e)});class at extends J{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==j.array)return P(n,{code:I.invalid_type,expected:j.array,received:n.parsedType}),B;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,c=n.data.length<s.exactLength.value;(a||c)&&(P(n,{code:a?I.too_big:I.too_small,minimum:c?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(P(n,{code:I.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(P(n,{code:I.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,c)=>s.type._parseAsync(new mt(n,a,n.path,c)))).then(a=>Le.mergeArray(r,a));const i=[...n.data].map((a,c)=>s.type._parseSync(new mt(n,a,n.path,c)));return Le.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new at({...this._def,minLength:{value:t,message:N.toString(n)}})}max(t,n){return new at({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new at({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(t){return this.min(1,t)}}at.create=(e,t)=>new at({type:e,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...Q(t)});function un(e){if(e instanceof _e){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ht.create(un(r))}return new _e({...e._def,shape:()=>t})}else return e instanceof at?new at({...e._def,type:un(e.element)}):e instanceof ht?ht.create(un(e.unwrap())):e instanceof Lt?Lt.create(un(e.unwrap())):e instanceof gt?gt.create(e.items.map(t=>un(t))):e}class _e extends J{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=ne.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==j.object){const d=this._getOrReturnCtx(t);return P(d,{code:I.invalid_type,expected:j.object,received:d.parsedType}),B}const{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof St&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||c.push(d);const l=[];for(const d of a){const u=i[d],f=s.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new mt(s,f,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof St){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(d==="strict")c.length>0&&(P(s,{code:I.unrecognized_keys,keys:c}),r.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=s.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new mt(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.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=>Le.mergeObjectSync(r,d)):Le.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return N.errToObj,new _e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,i,a,c;const l=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&a!==void 0?a:r.defaultError;return n.code==="unrecognized_keys"?{message:(c=N.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new _e({...this._def,unknownKeys:"strip"})}passthrough(){return new _e({...this._def,unknownKeys:"passthrough"})}extend(t){return new _e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new _e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:F.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new _e({...this._def,catchall:t})}pick(t){const n={};return ne.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new _e({...this._def,shape:()=>n})}omit(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new _e({...this._def,shape:()=>n})}deepPartial(){return un(this)}partial(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}),new _e({...this._def,shape:()=>n})}required(t){const n={};return ne.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ht;)i=i._def.innerType;n[r]=i}}),new _e({...this._def,shape:()=>n})}keyof(){return hl(ne.objectKeys(this.shape))}}_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:St.create(),typeName:F.ZodObject,...Q(t)});_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:St.create(),typeName:F.ZodObject,...Q(t)});_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:St.create(),typeName:F.ZodObject,...Q(t)});class er extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(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 a=i.map(c=>new Ve(c.ctx.common.issues));return P(n,{code:I.invalid_union,unionErrors:a}),B}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const l of r){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&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=a.map(l=>new Ve(l));return P(n,{code:I.invalid_union,unionErrors:c}),B}}get options(){return this._def.options}}er.create=(e,t)=>new er({options:e,typeName:F.ZodUnion,...Q(t)});const vt=e=>e instanceof rr?vt(e.schema):e instanceof ct?vt(e.innerType()):e instanceof sr?[e.value]:e instanceof Nt?e.options:e instanceof ir?ne.objectValues(e.enum):e instanceof or?vt(e._def.innerType):e instanceof Xn?[void 0]:e instanceof qn?[null]:e instanceof ht?[void 0,...vt(e.unwrap())]:e instanceof Lt?[null,...vt(e.unwrap())]:e instanceof eo||e instanceof cr?vt(e.unwrap()):e instanceof ar?vt(e._def.innerType):[];class ds extends J{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.object)return P(n,{code:I.invalid_type,expected:j.object,received:n.parsedType}),B;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);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}):(P(n,{code:I.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const i of n){const a=vt(i.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of a){if(s.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);s.set(c,i)}}return new ds({typeName:F.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Q(r)})}}function mi(e,t){const n=wt(e),r=wt(t);if(e===t)return{valid:!0,data:e};if(n===j.object&&r===j.object){const s=ne.objectKeys(t),i=ne.objectKeys(e).filter(c=>s.indexOf(c)!==-1),a={...e,...t};for(const c of i){const l=mi(e[c],t[c]);if(!l.valid)return{valid:!1};a[c]=l.data}return{valid:!0,data:a}}else if(n===j.array&&r===j.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let i=0;i<e.length;i++){const a=e[i],c=t[i],l=mi(a,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return n===j.date&&r===j.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class tr extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(i,a)=>{if(pi(i)||pi(a))return B;const c=mi(i.value,a.value);return c.valid?((hi(i)||hi(a))&&n.dirty(),{status:n.value,value:c.data}):(P(r,{code:I.invalid_intersection_types}),B)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}tr.create=(e,t,n)=>new tr({left:e,right:t,typeName:F.ZodIntersection,...Q(n)});class gt extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.array)return P(r,{code:I.invalid_type,expected:j.array,received:r.parsedType}),B;if(r.data.length<this._def.items.length)return P(r,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new mt(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Le.mergeArray(n,a)):Le.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new gt({...this._def,rest:t})}}gt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gt({items:e,typeName:F.ZodTuple,rest:null,...Q(t)})};class nr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.object)return P(r,{code:I.invalid_type,expected:j.object,received:r.parsedType}),B;const s=[],i=this._def.keyType,a=this._def.valueType;for(const c in r.data)s.push({key:i._parse(new mt(r,c,r.path,c)),value:a._parse(new mt(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Le.mergeObjectAsync(n,s):Le.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof J?new nr({keyType:t,valueType:n,typeName:F.ZodRecord,...Q(r)}):new nr({keyType:ot.create(),valueType:t,typeName:F.ZodRecord,...Q(n)})}}class Xr extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.map)return P(r,{code:I.invalid_type,expected:j.map,received:r.parsedType}),B;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,l],d)=>({key:s._parse(new mt(r,c,r.path,[d,"key"])),value:i._parse(new mt(r,l,r.path,[d,"value"]))}));if(r.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of a){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return B;(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 a){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return B;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}Xr.create=(e,t,n)=>new Xr({valueType:t,keyType:e,typeName:F.ZodMap,...Q(n)});class qt extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==j.set)return P(r,{code:I.invalid_type,expected:j.set,received:r.parsedType}),B;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(P(r,{code:I.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(P(r,{code:I.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const d=new Set;for(const u of l){if(u.status==="aborted")return B;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...r.data.values()].map((l,d)=>i._parse(new mt(r,l,r.path,d)));return r.common.async?Promise.all(c).then(l=>a(l)):a(c)}min(t,n){return new qt({...this._def,minSize:{value:t,message:N.toString(n)}})}max(t,n){return new qt({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}qt.create=(e,t)=>new qt({valueType:e,minSize:null,maxSize:null,typeName:F.ZodSet,...Q(t)});class gn extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.function)return P(n,{code:I.invalid_type,expected:j.function,received:n.parsedType}),B;function r(c,l){return Kr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),wn].filter(d=>!!d),issueData:{code:I.invalid_arguments,argumentsError:l}})}function s(c,l){return Kr({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Vr(),wn].filter(d=>!!d),issueData:{code:I.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof kn){const c=this;return Ue(async function(...l){const d=new Ve([]),u=await c._def.args.parseAsync(l,i).catch(h=>{throw d.addIssue(r(l,h)),d}),f=await Reflect.apply(a,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(h=>{throw d.addIssue(s(f,h)),d})})}else{const c=this;return Ue(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new Ve([r(l,d.error)]);const u=Reflect.apply(a,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new Ve([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new gn({...this._def,args:gt.create(t).rest(Vt.create())})}returns(t){return new gn({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new gn({args:t||gt.create([]).rest(Vt.create()),returns:n||Vt.create(),typeName:F.ZodFunction,...Q(r)})}}class rr extends J{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})}}rr.create=(e,t)=>new rr({getter:e,typeName:F.ZodLazy,...Q(t)});class sr extends J{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return P(n,{received:n.data,code:I.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:t.data}}get value(){return this._def.value}}sr.create=(e,t)=>new sr({value:e,typeName:F.ZodLiteral,...Q(t)});function hl(e,t){return new Nt({values:e,typeName:F.ZodEnum,...Q(t)})}class Nt extends J{constructor(){super(...arguments),Bn.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{expected:ne.joinValues(r),received:n.parsedType,code:I.invalid_type}),B}if(Yr(this,Bn)||dl(this,Bn,new Set(this._def.values)),!Yr(this,Bn).has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{received:n.data,code:I.invalid_enum_value,options:r}),B}return Ue(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 Nt.create(t,{...this._def,...n})}exclude(t,n=this._def){return Nt.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Bn=new WeakMap;Nt.create=hl;class ir extends J{constructor(){super(...arguments),Gn.set(this,void 0)}_parse(t){const n=ne.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==j.string&&r.parsedType!==j.number){const s=ne.objectValues(n);return P(r,{expected:ne.joinValues(s),received:r.parsedType,code:I.invalid_type}),B}if(Yr(this,Gn)||dl(this,Gn,new Set(ne.getValidEnumValues(this._def.values))),!Yr(this,Gn).has(t.data)){const s=ne.objectValues(n);return P(r,{received:r.data,code:I.invalid_enum_value,options:s}),B}return Ue(t.data)}get enum(){return this._def.values}}Gn=new WeakMap;ir.create=(e,t)=>new ir({values:e,typeName:F.ZodNativeEnum,...Q(t)});class kn extends J{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==j.promise&&n.common.async===!1)return P(n,{code:I.invalid_type,expected:j.promise,received:n.parsedType}),B;const r=n.parsedType===j.promise?n.data:Promise.resolve(n.data);return Ue(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}kn.create=(e,t)=>new kn({type:e,typeName:F.ZodPromise,...Q(t)});class ct extends J{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:a=>{P(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(n.value==="aborted")return B;const l=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return l.status==="aborted"?B:l.status==="dirty"||n.value==="dirty"?hn(l.value):l});{if(n.value==="aborted")return B;const c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?B:c.status==="dirty"||n.value==="dirty"?hn(c.value):c}}if(s.type==="refinement"){const a=c=>{const l=s.refinement(c,i);if(r.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(r.common.async===!1){const c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?B:(c.status==="dirty"&&n.dirty(),a(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?B:(c.status==="dirty"&&n.dirty(),a(c.value).then(()=>({status:n.value,value:c.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jt(a))return a;const c=s.transform(a.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:r.data,path:r.path,parent:r}).then(a=>Jt(a)?Promise.resolve(s.transform(a.value,i)).then(c=>({status:n.value,value:c})):a);ne.assertNever(s)}}ct.create=(e,t,n)=>new ct({schema:e,typeName:F.ZodEffects,effect:t,...Q(n)});ct.createWithPreprocess=(e,t,n)=>new ct({schema:t,effect:{type:"preprocess",transform:e},typeName:F.ZodEffects,...Q(n)});class ht extends J{_parse(t){return this._getType(t)===j.undefined?Ue(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ht.create=(e,t)=>new ht({innerType:e,typeName:F.ZodOptional,...Q(t)});class Lt extends J{_parse(t){return this._getType(t)===j.null?Ue(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Lt.create=(e,t)=>new Lt({innerType:e,typeName:F.ZodNullable,...Q(t)});class or extends J{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===j.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}or.create=(e,t)=>new or({innerType:e,typeName:F.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Q(t)});class ar extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Qn(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ve(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ar.create=(e,t)=>new ar({innerType:e,typeName:F.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Q(t)});class qr extends J{_parse(t){if(this._getType(t)!==j.nan){const r=this._getOrReturnCtx(t);return P(r,{code:I.invalid_type,expected:j.nan,received:r.parsedType}),B}return{status:"valid",value:t.data}}}qr.create=e=>new qr({typeName:F.ZodNaN,...Q(e)});const Ef=Symbol("zod_brand");class eo extends J{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class _r extends J{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?B:i.status==="dirty"?(n.dirty(),hn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?B:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new _r({in:t,out:n,typeName:F.ZodPipeline})}}class cr extends J{_parse(t){const n=this._def.innerType._parse(t),r=s=>(Jt(s)&&(s.value=Object.freeze(s.value)),s);return Qn(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}cr.create=(e,t)=>new cr({innerType:e,typeName:F.ZodReadonly,...Q(t)});function la(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ml(e,t={},n){return e?Sn.create().superRefine((r,s)=>{var i,a;const c=e(r);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=la(t,r),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;s.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=la(t,r),d=(a=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...l,fatal:d})}}):Sn.create()}const If={object:_e.lazycreate};var F;(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"})(F||(F={}));const xf=(e,t={message:`Input not instance of ${e.name}`})=>ml(n=>n instanceof e,t),gl=ot.create,yl=Mt.create,Tf=qr.create,Cf=Dt.create,_l=Jn.create,Af=Xt.create,Of=Qr.create,Pf=Xn.create,jf=qn.create,Mf=Sn.create,Df=Vt.create,Nf=St.create,Lf=Jr.create,$f=at.create,Uf=_e.create,Ff=_e.strictCreate,Bf=er.create,Gf=ds.create,Hf=tr.create,Wf=gt.create,zf=nr.create,Zf=Xr.create,Vf=qt.create,Kf=gn.create,Yf=rr.create,Qf=sr.create,Jf=Nt.create,Xf=ir.create,qf=kn.create,da=ct.create,ep=ht.create,tp=Lt.create,np=ct.createWithPreprocess,rp=_r.create,sp=()=>gl().optional(),ip=()=>yl().optional(),op=()=>_l().optional(),ap={string:e=>ot.create({...e,coerce:!0}),number:e=>Mt.create({...e,coerce:!0}),boolean:e=>Jn.create({...e,coerce:!0}),bigint:e=>Dt.create({...e,coerce:!0}),date:e=>Xt.create({...e,coerce:!0})},cp=B;var o=Object.freeze({__proto__:null,defaultErrorMap:wn,setErrorMap:tf,getErrorMap:Vr,makeIssue:Kr,EMPTY_PATH:nf,addIssueToContext:P,ParseStatus:Le,INVALID:B,DIRTY:hn,OK:Ue,isAborted:pi,isDirty:hi,isValid:Jt,isAsync:Qn,get util(){return ne},get objectUtil(){return fi},ZodParsedType:j,getParsedType:wt,ZodType:J,datetimeRegex:pl,ZodString:ot,ZodNumber:Mt,ZodBigInt:Dt,ZodBoolean:Jn,ZodDate:Xt,ZodSymbol:Qr,ZodUndefined:Xn,ZodNull:qn,ZodAny:Sn,ZodUnknown:Vt,ZodNever:St,ZodVoid:Jr,ZodArray:at,ZodObject:_e,ZodUnion:er,ZodDiscriminatedUnion:ds,ZodIntersection:tr,ZodTuple:gt,ZodRecord:nr,ZodMap:Xr,ZodSet:qt,ZodFunction:gn,ZodLazy:rr,ZodLiteral:sr,ZodEnum:Nt,ZodNativeEnum:ir,ZodPromise:kn,ZodEffects:ct,ZodTransformer:ct,ZodOptional:ht,ZodNullable:Lt,ZodDefault:or,ZodCatch:ar,ZodNaN:qr,BRAND:Ef,ZodBranded:eo,ZodPipeline:_r,ZodReadonly:cr,custom:ml,Schema:J,ZodSchema:J,late:If,get ZodFirstPartyTypeKind(){return F},coerce:ap,any:Mf,array:$f,bigint:Cf,boolean:_l,date:Af,discriminatedUnion:Gf,effect:da,enum:Jf,function:Kf,instanceof:xf,intersection:Hf,lazy:Yf,literal:Qf,map:Zf,nan:Tf,nativeEnum:Xf,never:Nf,null:jf,nullable:tp,number:yl,object:Uf,oboolean:op,onumber:ip,optional:ep,ostring:sp,pipeline:rp,preprocess:np,promise:qf,record:zf,set:Vf,strictObject:Ff,string:gl,symbol:Of,transformer:da,tuple:Wf,undefined:Pf,union:Bf,unknown:Df,void:Lf,NEVER:cp,ZodIssueCode:I,quotelessJson:ef,ZodError:Ve});const ua=o.enum(["app_start","sign_in","window_focus","surface_open"]),vl=o.object({id:o.string().min(1),state:o.enum(["active","paused","disabled"])}).passthrough(),lp=o.object({tenant_id:o.string().min(1),tenant_name:o.string().optional(),eligible:o.boolean(),endpoint:vl.nullable()}).passthrough(),dp=o.object({code:o.string(),message:o.string(),details:o.record(o.unknown()).optional(),retry_after_seconds:o.number().optional()}).passthrough(),up=o.object({code:o.string().min(1),count:o.number().int().nonnegative(),session:o.string().min(1).nullable().optional().catch(null)}).passthrough().nullable().optional().catch(null),ZS=o.object({capability:o.number(),consent_account_guard:o.boolean().optional(),state:o.enum(["ready","signed_out","unavailable","update_required"]),account_id:o.string().nullable(),tenant_id:o.string().nullable(),surface_state:o.enum(["A","B","C","D","E","F","G"]).nullable(),visibility:o.object({settings:o.boolean(),inbox:o.boolean(),account_door:o.boolean(),onboarding:o.boolean()}),update_required:o.boolean(),local:o.object({enabled:o.boolean(),onboarding:o.string(),session:o.string()}),status:o.object({tenants:o.array(lp)}).passthrough().nullable(),consent:o.object({version:o.string().min(1).max(128),text:o.string().min(1).refine(e=>new TextEncoder().encode(e).length<=2048,"Consent exceeds the served-text contract"),source:o.enum(["served","cached","embedded"])}).nullable(),error:dp.nullable(),state_note:o.string().nullable().optional(),read_only:o.boolean().optional(),delivery_hold:up}).passthrough(),fp=o.object({version:o.string().min(1),consented_at:o.string().min(1),consented_via:o.enum(["dialog","settings"]),current:o.boolean()}).passthrough(),VS=o.object({endpoint:vl.extend({tenant_id:o.string().min(1),label:o.string().optional(),consent:fp.nullable().optional(),created_at:o.string().optional(),updated_at:o.string().optional()}).nullable(),settings:o.object({tenant_id:o.string().min(1),eligible:o.boolean(),consent_version:o.string().optional(),consent_required:o.boolean()}).passthrough()}).passthrough(),pp=o.object({kind:o.enum(["endpoint","account"]).optional(),endpoint_id:o.string().min(1).optional(),account_id:o.string().min(1).optional()}).passthrough().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id").refine(e=>e.kind===void 0||(e.kind==="endpoint"?e.endpoint_id!==void 0:e.account_id!==void 0),"An allowlist target's kind must agree with the id it carries"),fa=o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:pp,id:o.string().optional()}).passthrough(),pa=o.object({mode:o.enum(["class_default","listed_only"]),allow:o.number(),deny:o.number()}).passthrough(),KS=o.object({allowlist:o.object({tenant_id:o.string().min(1),entries:o.array(fa)}).passthrough(),view:o.object({tenant_id:o.string().nullable(),entries:o.array(fa),directions:o.object({send:pa,receive:pa}),class_default:o.literal("cos_cos"),cues:o.object({allow_entry_switches_direction_to_listed_only:o.boolean(),listed_only_affects:o.string(),removing_allow_does_not_stop_open_thread:o.boolean(),deny_stops_pair_both_directions:o.boolean()}).passthrough()}).passthrough()}).passthrough();function YS(e,t){if(!e||!t||e.account_id!==t||e.capability<1||e.state!=="ready"||e.update_required||e.surface_state!=="B"||!e.visibility.onboarding||!e.tenant_id)return null;const n=e.status?.tenants.filter(r=>r.tenant_id===e.tenant_id);return n?.length!==1||n[0].eligible!==!0||n[0].endpoint!==null?null:{accountId:t,tenantId:e.tenant_id}}function QS(e){const t=e?.consent;return t&&(t.source==="served"||t.source==="cached")?t:null}const hp=8,gi=["aida","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh"],mp=6*1024,gp=512;function es(e,t,n){let r=new TextEncoder().encode(`${t}${e.size?`?${e}`:""}`).length;const s=[];for(const i of n){if(s.length===gp)break;const c=new URLSearchParams({order_ids:i}).toString().length+1;if(r+c>mp)break;e.append("order_ids",i),s.push(i),r+=c}return s}function yp(e,t,n){return es(new URLSearchParams(n),t,e)}const k=o.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),Cr=o.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),Ar=o.string().min(1).max(32768),_p=/^[a-f0-9]{12}$/,L=o.string().regex(_p),Ds=o.string().regex(/^[a-f0-9]{12}$/),Ns=o.string().min(1).max(128),vp=o.string().min(1).max(4096),Ls=o.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),Or=o.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),ha=o.string().regex(/^[a-f0-9]{32}$/),bp=/^(\/|[A-Za-z]:[\\/])/,$s=o.string().min(1).max(4096).regex(bp),ma=/^[a-f0-9]{32}$/,te=o.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),ga=o.string().min(1).max(512).nullish(),ln=o.string().regex(/^[A-Za-z0-9_-]{1,128}$/),ya=o.string().regex(/^ap_[0-9a-hjkmnp-tv-z]{1,64}$/),Mn=o.string().regex(/^la_[0-9a-f]{16}$/),Dn=o.string().min(1).max(128).regex(/^[A-Za-z0-9_.:-]+$/),_a=o.object({data_b64:o.string().min(1).max(1e6),mime_type:o.enum(["image/png","image/jpeg","image/gif","image/webp"]),origin_path:o.string().max(4096).optional()}).strict(),wp=o.object({digest:o.string().regex(/^[0-9a-f]{32}$/),name:o.string().max(1024).optional(),mime_type:o.string().max(255).optional(),bytes:o.number().int().min(0).optional(),path:o.string().max(4096).optional()}).strict(),va=2e5,ba=8,Sp=256,kp=100,wa=16,Rp=256,Ep=100,Ip=200,xp=1e6,Tp=o.enum(["auto","none","minimal","low","medium","high","xhigh","max"]),Oe=o.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),Pr=o.object({kind:o.enum(["agent","team"]),name:Oe}).strict(),bl=o.enum(["claude","codex","omp"]),Cp=o.record(o.string(),o.array(o.string().min(1).max(512)).max(5e3)),Sa={sources:o.array(bl).max(3).optional(),sessionIds:Cp.optional(),all:o.boolean().optional(),includeSubagents:o.boolean().optional(),includeClearedSegments:o.boolean().optional(),includeMemory:o.boolean().optional(),includeInstructions:o.boolean().optional(),maxSessions:o.number().int().min(1).max(5e3).optional()},Us=o.object({provider:o.string().min(1).max(128),model_id:o.string().min(1).max(512),reasoning_effort:o.string().min(1).max(64).nullable()}).strict(),ka=o.object({kind:o.enum(["role","specialist"]).optional(),description:o.string().max(8e3).optional(),instructions:o.string().max(8e3).optional(),tools:o.array(o.string().min(1).max(128)).max(256).optional(),effort:o.string().max(64).optional(),delegate:o.boolean().optional(),action_class:o.enum(["reactive","proactive"]).optional()}).strict(),Ra=o.object({name:o.string().min(1).max(64).optional(),description:o.string().max(8e3).optional(),manager:Oe.optional(),members:o.array(o.object({role:Oe,count:o.number().int().min(1).max(16),kind:o.enum(["agent","team"]),tier:o.enum(["lo","med","hi"]).nullable().optional(),effort:Tp.nullable().optional()}).strict()).max(128).optional(),instructions:o.string().max(8e3).optional(),project:o.string().max(8e3).optional()}).strict(),Ap=o.record(o.array(o.string().max(1024)).max(100)),Ea=o.enum(["minutes","hours","days"]);function Op(e){return!/^\.+$/.test(e)}const JS=e=>Hr.safeParse(e).success,Hr=o.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(Op),Ia=o.enum(["str","int","float","bool","list","dict"]),xa=o.string().max(16384),Pp=2e3,Ta=o.string().min(1).max(Pp),Ca=o.string().min(1).max(64),jp=o.string().min(1).max(64),Mp=o.string().min(1).max(64),Aa=o.object({is_active:o.boolean().nullish(),one_time:o.boolean().nullish(),start_time_utc:o.string().max(64).nullish(),end_time_utc:o.string().max(64).nullish()}).strict(),Dp=o.object({conversation_length:o.number().int().optional(),detail_length:o.number().int().optional(),max_learnings_history:o.number().int().optional(),hosting:o.string().max(256).optional(),model_name:o.string().max(1024).optional(),auto_save_conversation:o.boolean().optional()}).strict(),yi=128,Oa=2e3,Pa=8e3,ja=64,Ma=64,us=e=>[...e].length,_i=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,Np=e=>e===9||e===10||e===11||e===12||e===13||e===133,Lp=e=>e<=31||e>=127&&e<=159,$p=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),Up=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,jr=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},wl=e=>{const t=[...e];let n=0,r=t.length;for(;n<r&&_i(t[n].codePointAt(0)??0);)n++;for(;r>n&&_i(t[r-1].codePointAt(0)??0);)r--;return t.slice(n,r).join("")},Fp=e=>{let t="",n=!1;for(const r of e){if(_i(r.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=r}return t};function Bp(e){const t=wl(e);if(!t)return"must not be empty";if(us(t)>yi)return`must be at most ${yi} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(jr(t,Up))return"must not contain Unicode bidirectional override characters";if(jr(t,Np))return"must not contain whitespace";if(jr(t,Lp))return"must not contain control characters";if(jr(t,$p))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 XS(e){return Fp(wl(e).normalize("NFKC").toLowerCase())}function Gp(e){return e.trim()?us(e)>Oa?`must be at most ${Oa} characters`:null:"must not be empty"}function Hp(e){return e.trim()?us(e)>Pa?`must be at most ${Pa} characters`:null:"must not be empty"}function Wp(e){if(e.length>Ma)return`must hold at most ${Ma} items`;for(const t of e)if(!t.trim()||us(t)>ja)return`must hold items of 1 to ${ja} characters`;return null}const zp=e=>Bp(e)===null,Zp=o.string().refine(zp,{message:"That is not a name the hub can publish."}),Vp=o.string().refine(e=>Hp(e)===null,{message:"That instruction body cannot be published."}),Kp=o.string().refine(e=>Gp(e)===null,{message:"That description cannot be published."}),Yp=o.array(o.string()).refine(e=>Wp(e)===null,{message:"That tool list cannot be published."}),Fs={requestId:te.optional(),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()},Da=o.object({name:Zp,description:Kp,instructions:Vp,kind:o.enum(["role","specialist"]),when_to_use:o.string(),tools:Yp,effort:o.string(),delegate:o.boolean(),version:o.string(),categories:o.array(o.string()),tags:o.array(o.string())}).partial().strict(),Qp=o.enum(["team","agent"]),Jp=o.string().min(1).max(64),Xp=o.string().min(1).max(256),Sl=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Bs=o.string().regex(Sl,{message:"Letters, digits, dot, underscore and dash; no spaces."}),qp=["planning","active","qa","validation","done","paused","archived"],Na=o.enum(qp),Mr=o.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),La=o.array(o.string().min(1).max(24)).max(8),Tt=o.string().min(1).max(64),eh=1e3,$a=240,Ua=80,th=256,nh=100,rh=200,sh=/^[a-z0-9][a-z0-9_-]{0,23}$/;function qS(e){return e?Sl.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 ek(e){return sh.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Dr=o.enum(["agent","team","skill"]),Fa=o.enum(gi),ih=o.object({visible:o.array(Fa).max(gi.length),more:o.array(Fa).max(gi.length)}).strict(),oh=o.discriminatedUnion("op",[o.object({op:o.literal("capabilities")}).strict(),o.object({op:o.literal("runtimes.list")}).strict(),o.object({op:o.literal("profiles.list")}).strict(),o.object({op:o.literal("profiles.get"),name:Oe}).strict(),o.object({op:o.literal("imports.sources")}).strict(),o.object({op:o.literal("imports.sessions"),source:bl,includeSubagents:o.boolean().optional()}).strict(),o.object({op:o.literal("imports.preview"),...Sa}).strict(),o.object({op:o.literal("imports.start"),...Sa}).strict(),o.object({op:o.literal("imports.status"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("imports.cancel"),jobId:o.string().min(1).max(128)}).strict(),o.object({op:o.literal("profiles.update"),name:Oe,requestId:te,fields:ka,expectedDefinitionRevision:ga.optional()}).strict(),o.object({op:o.literal("profiles.install"),name:Oe,requestId:te}).strict(),o.object({op:o.literal("profiles.create"),name:Oe,requestId:te,fields:ka.extend({description:o.string().max(8e3),instructions:o.string().min(1).max(8e3)})}).strict(),o.object({op:o.literal("hub.updates")}).strict(),o.object({op:o.literal("hub.skillPull"),requestId:te,hubId:k,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:k.nullable(),localAlias:Oe,subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.skillSubscribe"),requestId:te,hubId:k,hubSource:o.string().min(1).max(2048),visibility:o.enum(["public","org"]),tenantId:k.nullable(),localAlias:Oe}).strict(),o.object({op:o.literal("hub.skillUnpull"),requestId:te,linkId:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("hub.skillPublish"),requestId:te,dryRun:o.boolean(),sourceSkill:Oe,localAlias:Oe,visibility:o.enum(["public","org"]),tenantId:k.nullable(),subscribe:o.boolean(),autoPush:o.boolean(),confirmPublicEgress:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("hub.links"),kind:o.enum(["agent","team","skill"]).optional()}).strict(),o.object({op:o.literal("hub.policy"),requestId:te,linkId:o.string().min(1).max(256),expectedPolicyRevision:o.string().min(1).max(256),subscribe:o.boolean().optional(),autoPush:o.boolean().optional(),confirmPublicEgress:o.boolean().optional()}).strict(),o.object({op:o.literal("hub.check"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Dr.optional(),name:Oe.optional()}).strict(),o.object({op:o.literal("hub.apply"),requestId:te,previewReceipt:o.string().min(1).max(4096).optional(),confirmApply:o.literal(!0).optional(),linkId:o.string().min(1).max(256).optional(),direction:o.literal("pull").optional(),kind:Dr.optional(),name:Oe.optional(),prefer:o.enum(["local","remote"]).optional(),acknowledgeUnknownBaseline:o.boolean().optional(),dryRun:o.boolean().optional(),resolveSource:o.literal(!0).optional(),hubSource:o.string().min(1).max(2048).optional(),visibility:o.enum(["public","org"]).optional(),tenantId:o.string().min(1).max(128).nullable().optional()}).strict(),o.object({op:o.literal("hub.applyAll"),requestId:te,kind:Dr.optional()}).strict(),o.object({op:o.literal("hub.retry"),requestId:te,linkId:o.string().min(1).max(256).optional(),direction:o.enum(["pull","push"]).optional(),kind:Dr.optional(),name:Oe.optional()}).strict(),o.object({op:o.literal("hub.push"),requestId:te,linkId:o.string().min(1).max(256),direction:o.literal("push"),dryRun:o.boolean(),previewReceipt:o.string().min(1).max(4096).optional(),confirmPublish:o.literal(!0).optional()}).strict(),o.object({op:o.literal("teams.list")}).strict(),o.object({op:o.literal("teams.get"),name:Oe}).strict(),o.object({op:o.literal("teams.effective"),name:Oe}).strict(),o.object({op:o.literal("teams.update"),name:Oe,requestId:te,fields:Ra,expectedDefinitionRevision:ga.optional()}).strict(),o.object({op:o.literal("teams.create"),requestId:te,fields:Ra.extend({name:o.string().min(1).max(64)})}).strict(),o.object({op:o.literal("sessions.list"),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional(),include_peers:o.boolean().optional(),scope_kind:Qp.optional(),scope_name:Jp.optional(),cursor:Xp.optional(),with_counts:o.boolean().optional(),sort:o.literal("activity").optional()}).strict(),o.object({op:o.literal("delegated_cleanup_notice.ack")}).strict(),o.object({op:o.literal("sessions.search"),q:o.string().min(1).max(Sp),limit:o.number().int().min(1).max(500).optional(),include_archived:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.archive"),sessionId:L,archived:o.boolean()}).strict(),o.object({op:o.literal("sessions.delete"),sessionId:L,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.create"),requestId:te,cwd:o.string().min(1).max(4096).optional(),target:Pr.optional(),purpose:o.literal("agents-config").optional(),model:Us.optional(),draftId:L.optional(),peer:ln.optional()}).strict(),o.object({op:o.literal("sessions.preview"),requestId:te,cwd:o.string().min(1).max(4096),target:Pr.optional(),model:Us.optional()}).strict(),o.object({op:o.literal("sessions.draft"),requestId:te,cwd:o.string().min(1).max(4096),target:Pr.optional(),model:Us.optional()}).strict(),o.object({op:o.literal("sessions.get"),sessionId:L,journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.files"),sessionId:L,scope:o.enum(["family","self"]).optional(),kind:o.string().max(256).optional(),q:o.string().max(256).optional(),sort:o.enum(["recent","name","kind","modified","created","size"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(8192).optional()}).strict(),o.object({op:o.literal("sessions.files.materialise"),sessionId:L,fileId:o.string().regex(/^[a-f0-9]{16}$/)}).strict(),o.object({op:o.literal("sessions.history"),sessionId:L,beforeId:k.optional(),limit:o.number().int().min(1).max(500).optional(),openFrame:o.boolean().optional(),journalOrder:o.boolean().optional(),orderIds:o.array(o.string().min(1).max(128)).max(512).optional(),peerJournalSource:o.boolean().optional(),sourceRead:o.enum(["metadata","payload"]).optional(),expectedJournalGeneration:o.string().min(1).max(128).optional()}).strict(),o.object({op:o.literal("sessions.checkpoints"),sessionId:L}).strict(),o.object({op:o.literal("sessions.checkpoints.warm"),sessionId:L,ids:o.array(k).max(wa).optional(),limit:o.number().int().min(1).max(wa).optional()}).strict(),o.object({op:o.literal("sessions.find"),sessionId:L,q:o.string().min(1).max(Rp),limit:o.number().int().min(1).max(Ip).optional()}).strict(),o.object({op:o.literal("subagents.transcript"),sessionId:L,childId:L,beforeId:k.optional(),limit:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("sessions.message"),sessionId:L,requestId:te,text:o.string().max(va),images:o.array(_a).max(ba).optional(),files:o.array(wp).max(hp).optional(),mode:o.enum(["prompt","steer"]).optional(),inputMode:o.enum(["typed","dictated","mixed"]).optional(),inputPath:o.string().max(1024).optional()}).strict(),o.object({op:o.literal("sessions.command"),sessionId:L,requestId:te,command:o.string().regex(/^\/?[A-Za-z]+$/).max(64),args:o.string().max(va).optional(),images:o.array(_a).max(ba).optional()}).strict(),o.object({op:o.literal("sessions.move"),sessionId:L,requestId:te,cwd:o.string().min(1).max(4096)}).strict(),o.object({op:o.literal("sessions.answer"),sessionId:L,epoch:k.optional(),requestId:k.optional(),value:o.string().max(32768).optional(),approved:o.boolean().optional(),questionIndex:o.number().int().min(0).optional(),askId:k.optional(),answers:o.record(o.string(),o.array(o.string().max(32768))).optional(),decline:o.boolean().optional(),revise:o.boolean().optional(),dismiss:o.boolean().optional(),reason:o.enum(["answered_in_chat","moot"]).optional()}).strict(),o.object({op:o.literal("sessions.seen"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("attention.seen"),items:o.array(o.object({sessionId:L,completionToken:o.string().uuid()}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("sessions.notified"),sessionId:L,completionToken:o.string().uuid()}).strict(),o.object({op:o.literal("tags.list")}).strict(),o.object({op:o.literal("tags.replace"),tags:o.array(o.object({id:o.string().optional(),name:o.string()}).strict())}).strict(),o.object({op:o.literal("sessions.tags"),expected_revision:o.string().optional(),sessionId:L,tags:o.array(o.string()),primary:o.string().nullable()}).strict(),o.object({op:o.literal("sessions.pin"),sessionId:L,pinned:o.boolean()}).strict(),o.object({op:o.literal("sessions.watch"),sessionId:L,subscriptionId:o.string().regex(ma),visible:o.boolean(),canNotify:o.boolean()}).strict(),o.object({op:o.literal("sessions.warm"),sessionId:L}).strict(),o.object({op:o.literal("sessions.interrupt"),sessionId:L,requestId:te}).strict(),o.object({op:o.literal("supplements.cancel"),sessionId:L,job:Ds,anchor:Ns}).strict(),o.object({op:o.literal("supplements.restart"),sessionId:L,job:Ds,anchor:Ns}).strict(),o.object({op:o.literal("supplements.steer"),sessionId:L,job:Ds,anchor:Ns,text:o.string().min(1).max(500)}).strict(),o.object({op:o.literal("sessions.variables.list"),sessionId:L}).strict(),o.object({op:o.literal("sessions.variables.create"),sessionId:L,key:Hr,value:xa,type:Ia}).strict(),o.object({op:o.literal("sessions.variables.update"),sessionId:L,key:Hr,value:xa,type:Ia}).strict(),o.object({op:o.literal("sessions.variables.delete"),sessionId:L,key:Hr}).strict(),o.object({op:o.literal("sessions.presence"),subscriptionId:o.string().regex(/^[a-f0-9]{1,64}$/),canNotify:o.boolean(),canNotifyKinds:o.array(o.enum(["complete","error"])).max(4),sessionId:o.string().regex(/^([a-f0-9]{12})?$/),window:o.object({exists:o.boolean(),focused:o.boolean(),visible:o.boolean(),minimized:o.boolean()}).strict()}).strict(),o.object({op:o.literal("legacy.models"),provider:o.string().max(128).optional(),sort:o.enum(["id","name","provider","recommended"]).optional(),direction:o.enum(["ascending","descending"]).optional()}).strict(),o.object({op:o.literal("legacy.models.providers")}).strict(),o.object({op:o.literal("auth.probe"),provider:k}).strict(),o.object({op:o.literal("legacy.agent.upload"),agentId:k}).strict(),o.object({op:o.literal("agent.publish"),agentId:k,document:Da.optional(),...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("agent.republish"),agentId:k,hubAgentId:k,expectedRemoteRevision:o.string().min(1).max(512).optional(),document:Da.optional(),...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("team.publish"),teamId:k,...Fs,visibility:o.literal("org").optional(),tenantId:k.optional()}).strict(),o.object({op:o.literal("team.pull"),teamId:k,tenantId:k.optional()}).strict(),o.object({op:o.literal("agent.nameAvailability"),name:o.string().min(1).max(yi)}).strict(),o.object({op:o.literal("legacy.agents.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional(),name:o.string().max(256).optional(),sort:o.string().max(64).optional(),direction:o.enum(["asc","desc"]).optional()}).strict(),o.object({op:o.literal("legacy.agent.get"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.history"),agentId:k,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(500).optional()}).strict(),o.object({op:o.literal("legacy.jobs.list"),agentId:k.optional(),status:o.string().max(64).optional()}).strict(),o.object({op:o.literal("legacy.job.get"),jobId:k}).strict(),o.object({op:o.literal("legacy.schedules.list"),page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedules.list"),agentId:k,page:o.number().int().min(1).optional(),perPage:o.number().int().min(1).max(100).optional()}).strict(),o.object({op:o.literal("legacy.agent.schedule.create"),agentId:k,schedule:Aa.extend({prompt:o.string().max(64e3),interval:o.number().int().min(1),unit:Ea})}).strict(),o.object({op:o.literal("legacy.schedule.get"),scheduleId:k}).strict(),o.object({op:o.literal("legacy.schedule.edit"),scheduleId:k,schedule:Aa.extend({prompt:o.string().max(64e3).nullish(),interval:o.number().int().min(1).nullish(),unit:Ea.nullish()})}).strict(),o.object({op:o.literal("legacy.schedule.remove"),scheduleId:k}).strict(),o.object({op:o.literal("legacy.agent.create"),agent:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.update"),agentId:k,update:o.record(o.unknown())}).strict(),o.object({op:o.literal("legacy.agent.delete"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.conversation.clear"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.get"),agentId:k}).strict(),o.object({op:o.literal("legacy.agent.systemPrompt.update"),agentId:k,systemPrompt:o.string().max(xp)}).strict(),o.object({op:o.literal("legacy.agent.download"),agentId:k}).strict(),o.object({op:o.literal("legacy.job.cancel"),jobId:k}).strict(),o.object({op:o.literal("commands.list")}).strict(),o.object({op:o.literal("commands.entities"),sessionId:L,command:k,name:o.string().max(128).optional()}).strict(),o.object({op:o.literal("models.catalogue"),live:o.boolean().optional(),scope:o.enum(["usable","all"]).optional()}).strict(),o.object({op:o.literal("usage.get"),provider:k.optional(),live:o.boolean().optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("quota.notice"),provider:k.optional(),model:o.string().min(1).max(200).optional(),refresh:o.boolean().optional()}).strict(),o.object({op:o.literal("analytics.get"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("analytics.models"),sessionId:L.optional(),sinceMs:o.number().int().nonnegative().optional(),untilMs:o.number().int().nonnegative().optional(),days:o.number().int().min(1).max(366).optional()}).strict(),o.object({op:o.literal("info.get")}).strict(),o.object({op:o.literal("sessions.report"),sessionId:L,recentLimit:o.number().int().min(0).max(50).optional()}).strict(),o.object({op:o.literal("skills.list"),sessionId:L.optional(),cwd:vp.optional(),name:k.optional()}).strict(),o.object({op:o.literal("sessions.failovers"),sessionId:L}).strict(),o.object({op:o.literal("sessions.credential"),sessionId:L,action:o.enum(["list","store","forget"]),key:Cr.optional(),value:Ar.optional(),confirmed:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.fork"),sessionId:L,requestId:te,message:o.string().max(2e5).optional(),boundary:o.enum(["next_safe","at_entry"]).optional(),entryId:o.string().max(128).optional(),autoTag:o.boolean().optional()}).strict(),o.object({op:o.literal("sessions.stop"),requestId:te,targets:o.array(L).min(1).max(100),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside"),sessionId:L,requestId:te,text:o.string().min(1).max(32768),asideId:te.optional(),subscriptionId:o.string().regex(ma).optional()}).strict(),o.object({op:o.literal("sessions.adopt"),sessionId:L,requestId:te,asideId:te,confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("sessions.aside.get"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("sessions.aside.close"),sessionId:L,asideId:te}).strict(),o.object({op:o.literal("wakes.list"),limit:o.number().int().min(1).max(500).optional(),includeDormant:o.boolean().optional()}).strict(),o.object({op:o.literal("wakes.create"),requestId:te,sessionId:L.optional(),cwd:o.string().min(1).max(4096).optional(),target:Pr.optional(),message:Ta,in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional(),title:o.string().min(1).max(200).optional()}).strict(),o.object({op:o.literal("wakes.edit"),sessionId:L,wakeId:Ca,message:Ta.optional(),in:o.string().min(1).max(64).optional(),at:o.string().min(1).max(64).optional(),every:o.string().min(1).max(64).optional(),until:o.string().min(1).max(64).optional(),limit:o.number().int().min(1).optional()}).strict(),o.object({op:o.literal("wakes.remove"),sessionId:L,wakeId:Ca}).strict(),o.object({op:o.literal("monitors.cancel"),sessionId:L,monitorId:jp}).strict(),o.object({op:o.literal("jobs.cancel"),sessionId:L,jobId:Mp}).strict(),o.object({op:o.literal("mcp.list"),sessionId:L}).strict(),o.object({op:o.literal("mcp.credentials.store"),sessionId:L,name:o.string().min(1).max(256),values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("mcp.control"),sessionId:L,control:o.object({action:o.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:Ls.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Or).optional(),url:o.string().max(4096).optional(),headers:o.record(Or).optional(),oauth:o.boolean().optional(),confirmed:o.boolean().optional(),operation_id:ha.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog"),cwd:$s.optional(),sessionId:L.optional()}).strict(),o.object({op:o.literal("mcp.catalog.control"),cwd:$s.optional(),control:o.object({action:o.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:Ls.optional(),scope:o.enum(["global","project"]).optional(),command:o.string().min(1).max(4096).optional(),args:o.array(o.string().max(8192)).max(128).optional(),env:o.record(Or).optional(),url:o.string().max(4096).optional(),headers:o.record(Or).optional(),confirmed:o.boolean().optional(),operation_id:ha.optional()}).strict()}).strict(),o.object({op:o.literal("mcp.catalog.credentials"),header:o.string().min(1).max(128).optional(),cwd:$s.optional(),name:Ls,values:o.record(o.string().min(1).max(128),o.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:o.array(o.string().min(1).max(128)).max(32)}).strict(),o.object({op:o.literal("radient.request"),control:o.object({operation:o.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","org_skills.list","org_skill.get","signup.resend"]),request_id:te.optional(),tenant_id:k.optional(),account_id:k.optional(),agent_id:k.optional(),comment_id:k.optional(),team_id:k.optional(),skill_id:k.optional(),query:o.record(o.union([o.string().max(1024),o.number().int()])).optional(),payload:o.record(o.unknown()).optional(),confirmed:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("providers.list")}).strict(),o.object({op:o.literal("accounts.list")}).strict(),o.object({op:o.literal("accounts.remove"),accountId:o.number().int().positive(),confirmed:o.literal(!0)}).strict(),o.object({op:o.literal("tunnel.setup.read"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.plan"),credentialId:o.number().int().positive().optional()}).strict(),o.object({op:o.literal("tunnel.setup.run"),credentialId:o.number().int().positive(),acceptMonthlyPrice:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("auth.start"),provider:k}).strict(),o.object({op:o.literal("auth.status"),id:k}).strict(),o.object({op:o.literal("auth.input"),id:k,promptId:k,value:Ar}).strict(),o.object({op:o.literal("auth.cancel"),id:k}).strict(),o.object({op:o.literal("auth.key"),provider:k,value:Ar}).strict(),o.object({op:o.literal("auth.logout"),provider:k}).strict(),o.object({op:o.literal("agent_messages.status"),boundary:ua}).strict(),o.object({op:o.literal("agent_messages.enable"),expected_account_id:k,tenant_id:k,state:o.literal("active"),consent_version:o.string().min(1).max(128),consented_via:o.literal("dialog")}).strict(),o.object({op:o.literal("agent_messages.settings"),tenant_id:k.optional()}).strict(),o.object({op:o.literal("agent_messages.settings.put"),expected_account_id:k,tenant_id:k.optional(),consent_version:o.string().min(1).max(128).optional(),consented_via:o.enum(["dialog","settings"]).optional(),label:o.string().min(1).max(128).optional(),state:o.enum(["active","paused","disabled"])}).strict(),o.object({op:o.literal("agent_messages.allowlist.get"),tenant_id:k.optional()}).strict(),o.object({op:o.literal("agent_messages.allowlist.put"),expected_account_id:k,tenant_id:k.optional(),entries:o.array(o.object({direction:o.enum(["send","receive"]),effect:o.enum(["allow","deny"]),target:o.object({endpoint_id:k.optional(),account_id:k.optional()}).strict().refine(e=>!!e.endpoint_id!=!!e.account_id,"An allowlist target names exactly one of endpoint_id or account_id")}).strict()).max(200)}).strict(),o.object({op:o.literal("team_bridge.conversations.list"),scope:o.literal("account").optional(),tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),cursor:o.string().min(1).max(64).optional(),before:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.get"),conversation_id:k,tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.create"),expected_account_id:k.optional(),tenant_id:k.optional(),kind:o.enum(["dm","group","channel"]),name:o.string().min(1).max(128).optional(),topic:o.string().min(1).max(512).optional(),visibility:o.enum(["private","tenant"]).optional(),agent_capable:o.boolean().optional(),members:o.array(o.object({account_id:k,kind:o.enum(["human","agent"]),endpoint_id:k.optional(),display_label:o.string().min(1).max(64)}).strict()).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.lifecycle"),expected_account_id:k.optional(),tenant_id:k.optional(),conversation_id:k,action:o.enum(["archive","unarchive","join","leave"])}).strict(),o.object({op:o.literal("team_bridge.conversations.join"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.conversations.notify"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),notify:o.enum(["all","mention","mute"])}).strict(),o.object({op:o.literal("team_bridge.conversations.members.add"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),members:o.array(o.object({account_id:k,kind:o.enum(["human","agent"]),endpoint_id:k.optional(),display_label:o.string().min(1).max(64)}).strict()).min(1).max(500)}).strict(),o.object({op:o.literal("team_bridge.conversations.members.remove"),expected_account_id:k.optional(),tenant_id:k.optional(),conversation_id:k,account_id:k}).strict(),o.object({op:o.literal("team_bridge.conversations.consent"),expected_account_id:k.optional(),conversation_id:k,account_id:k,decision:o.enum(["accept","decline"]),consent_version:o.string().min(1).max(128),tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.list"),conversation_id:k,tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),before_seq:o.number().int().nonnegative().optional(),endpoint_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.reactions.toggle"),conversation_id:k,message_id:k,tenant_id:k.optional(),emoji:o.string().min(1),active:o.boolean()}).strict(),o.object({op:o.literal("team_bridge.messages.send"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),client_ref:k,body:o.string().min(1),agent_label:o.string().min(1).max(64).optional(),thread_root_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.messages.replies"),conversation_id:k,message_id:k,tenant_id:k.optional(),limit:o.number().int().min(1).max(100).optional(),after_seq:o.number().int().nonnegative().optional()}).strict(),o.object({op:o.literal("team_bridge.read"),expected_account_id:k.optional(),conversation_id:k,tenant_id:k.optional(),seq:o.number().int().nonnegative().optional(),muted:o.boolean().optional()}).strict(),o.object({op:o.literal("team_bridge.unread"),scope:o.literal("account").optional(),tenant_id:k.optional()}).strict(),o.object({op:o.literal("team_bridge.directory"),tenant_id:k}).strict(),o.object({op:o.literal("team_bridge.status"),boundary:ua.optional()}).strict(),o.object({op:o.literal("settings.list")}).strict(),o.object({op:o.literal("settings.edit"),key:Cr,value:o.unknown().refine(e=>e!==void 0,"A setting value is required."),base:Ap.optional()}).strict(),o.object({op:o.literal("settings.reset"),key:Cr}).strict(),o.object({op:o.literal("tts.paths")}).strict(),o.object({op:o.literal("config.get")}).strict(),o.object({op:o.literal("config.update"),value:Dp}).strict(),o.object({op:o.literal("instructions.get")}).strict(),o.object({op:o.literal("instructions.update"),content:o.string().max(64e3)}).strict(),o.object({op:o.literal("credentials.list")}).strict(),o.object({op:o.literal("credentials.update"),key:Cr,value:Ar}).strict(),o.object({op:o.literal("peers.list")}).strict(),o.object({op:o.literal("networks.list")}).strict(),o.object({op:o.literal("networks.invite"),networkId:ln,role:o.enum(["read","drive","admin"]),deviceId:ln.optional()}).strict(),o.object({op:o.literal("networks.member.remove"),networkId:ln,deviceId:ln,confirm:o.string().min(1).max(256)}).strict(),o.object({op:o.literal("sessions.transfer"),sessionId:L,to:o.union([o.literal("local"),ln]),keep:o.boolean().optional(),waitS:o.number().min(0).max(300).optional(),requestId:te.optional()}).strict(),o.object({op:o.literal("approvals.list")}).strict(),o.object({op:o.literal("approvals.approve"),approvalId:ya}).strict(),o.object({op:o.literal("approvals.deny"),approvalId:ya}).strict(),o.object({op:o.literal("asks.list")}).strict(),o.object({op:o.literal("projects.list")}).strict(),o.object({op:o.literal("projects.get"),key:Tt}).strict(),o.object({op:o.literal("projects.create"),name:Bs,description:o.string().max($a).optional(),status:Na.optional(),tags:La.optional()}).strict(),o.object({op:o.literal("projects.update"),key:Tt,fields:o.object({name:Bs.optional(),title:o.string().max(80).optional(),owner:o.string().max(80).optional(),team:o.string().max(80).optional(),description:o.string().max($a).optional(),status:Na.optional(),progress:o.string().max(eh).optional(),tags:La.optional(),start_date:Mr.optional(),target_date:Mr.optional(),completed_at:Mr.optional(),estimate:o.number().positive().max(1e3).optional(),estimate_unit:o.enum(["points","days"]).optional()}).strict(),force_done:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.delete"),key:Tt,confirmed_name:Bs}).strict(),o.object({op:o.literal("projects.link"),key:Tt,sessionId:L}).strict(),o.object({op:o.literal("projects.unlink"),key:Tt,sessionId:L}).strict(),o.object({op:o.literal("projects.milestone"),key:Tt,name:o.string().min(1).max(Ua),targetDate:Mr.optional(),completed:o.boolean().optional()}).strict(),o.object({op:o.literal("projects.milestone.remove"),key:Tt,name:o.string().min(1).max(Ua)}).strict(),o.object({op:o.literal("projects.request_update"),key:Tt}).strict(),o.object({op:o.literal("projects.search"),q:o.string().min(1).max(th),limit:o.number().int().min(1).max(rh).optional()}).strict(),o.object({op:o.literal("aida.status")}).strict(),o.object({op:o.literal("aida.control"),action:o.enum(["open","pause","resume","greet","status"])}).strict(),o.object({op:o.literal("code_requests.list"),sessionId:L}).strict(),o.object({op:o.literal("code_requests.refresh"),sessionId:L,keys:o.array(o.string().min(1).max(512)).max(256).optional(),force:o.boolean().optional()}).strict(),o.object({op:o.literal("static.sign"),route:o.enum(["images","videos","audio","html"]),path:o.string().min(1),ttlS:o.number().int().min(1).max(3600).optional()}).strict(),o.object({op:o.literal("library.list"),scope:o.enum(["final","all"]).optional(),q:o.string().max(512).optional(),category:o.string().min(1).max(64).optional(),kind:o.string().min(1).max(64).optional(),origin_group:o.enum(["generated","created","mentioned"]).optional(),origin:o.string().min(1).max(64).optional(),tag:o.string().min(1).max(128).optional(),tag_mode:o.enum(["all","any"]).optional(),highlighted:o.boolean().optional(),organized:o.boolean().optional(),favorite:o.boolean().optional(),session:o.string().min(1).max(12).optional(),session_id:o.string().min(1).max(512).optional(),sort:o.enum(["recent","name","kind","size","created","modified","organized"]).optional(),order:o.enum(["asc","desc"]).optional(),limit:o.number().int().min(1).max(200).optional(),cursor:o.string().max(512).optional()}).strict(),o.object({op:o.literal("library.get"),id:Mn}).strict(),o.object({op:o.literal("library.update"),id:Mn,fields:o.object({name:o.string().max(200).optional(),description:o.string().max(2e3).optional(),favorite:o.boolean().optional(),locked:o.boolean().optional(),archived:o.boolean().optional()}).strict()}).strict(),o.object({op:o.literal("library.tags")}).strict(),o.object({op:o.literal("library.tags.create"),name:o.string().trim().min(1).max(24),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.update"),id:Dn,name:o.string().trim().min(1).max(24).optional(),category:o.string().min(1).max(64).optional()}).strict(),o.object({op:o.literal("library.tags.delete"),id:Dn}).strict(),o.object({op:o.literal("library.tags.merge"),id:Dn,into:Dn}).strict(),o.object({op:o.literal("library.tags.assign"),id:Mn,tags:o.array(Dn).max(64),primary:o.string().max(128).optional()}).strict(),o.object({op:o.literal("library.chat.link"),id:Mn,sessionId:L}).strict(),o.object({op:o.literal("library.chat.clear"),id:Mn}).strict(),o.object({op:o.literal("library.librarian"),action:o.enum(["status","open","pause","resume","run"]).optional()}).strict(),o.object({op:o.literal("sidebar_layout.get")}).strict(),o.object({op:o.literal("sidebar_layout.set"),layout:ih}).strict()]);oh.superRefine((e,t)=>{if(e.op.startsWith("team_bridge.")&&"expected_account_id"in e&&e.expected_account_id&&(!("tenant_id"in e)||!e.tenant_id)){t.addIssue({code:o.ZodIssueCode.custom,path:["tenant_id"],message:"Guarded conversation writes require an explicit tenant"});return}if(e.op==="hub.skillPull"||e.op==="hub.skillSubscribe"||e.op==="hub.skillPublish"){if(e.visibility==="public"&&e.tenantId!==null||e.visibility==="org"&&!e.tenantId){t.addIssue({code:o.ZodIssueCode.custom,message:"A skill destination requires explicit paired scope",path:["tenantId"]});return}if(e.op==="hub.skillPublish"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"An initial skill publication requires its reviewed draft receipt",path:["previewReceipt"]});return}}if(e.op==="hub.check"||e.op==="hub.apply"||e.op==="hub.retry"){const n=e.linkId!==void 0,r=e.kind!==void 0||e.name!==void 0;if(n&&r||e.op!=="hub.check"&&!n&&(!e.kind||!e.name)||e.op==="hub.retry"&&n&&!e.direction||e.direction==="push"&&!n){t.addIssue({code:o.ZodIssueCode.custom,message:"A hub action requires one unambiguous selector and an explicit retry direction",path:["linkId"]});return}}if(e.op==="hub.apply"&&(e.previewReceipt!==void 0||e.confirmApply!==void 0)&&(!e.linkId||e.dryRun||!e.previewReceipt||e.confirmApply!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"A viewed incoming application requires its scoped preview receipt and confirmation",path:["previewReceipt"]});return}if(e.op==="hub.apply"&&e.resolveSource===!0){const n=e.visibility==="public"&&e.tenantId===null||e.visibility==="org"&&typeof e.tenantId=="string"&&e.tenantId.length>0;if(!e.hubSource||!n||e.acknowledgeUnknownBaseline!==!0||e.linkId!==void 0||e.previewReceipt!==void 0||e.confirmApply!==void 0||e.prefer!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"Confirming a source requires its exact stated destination and the unknown-baseline acknowledgement, with no link, preview or preference",path:["hubSource"]});return}}if(e.op==="hub.push"&&(e.dryRun?e.previewReceipt!==void 0||e.confirmPublish!==void 0:!e.previewReceipt||e.confirmPublish!==!0)){t.addIssue({code:o.ZodIssueCode.custom,message:"A confirmed publication requires its reviewed preview receipt",path:["previewReceipt"]});return}if(e.op==="hub.policy"&&e.subscribe===void 0&&e.autoPush===void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"A hub policy change must name subscribe or autoPush",path:["subscribe"]});return}if((e.op==="team_bridge.conversations.list"||e.op==="team_bridge.unread")&&e.scope==="account"&&e.tenant_id!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"An account-scoped read cannot name a tenant",path:["scope"]});return}if(e.op==="team_bridge.conversations.list"&&e.scope==="account"&&e.before!==void 0){t.addIssue({code:o.ZodIssueCode.custom,message:"An account-scoped page uses cursor, not before",path:["before"]});return}if(e.op==="sessions.answer"){if(e.askId!==void 0){if(e.askId||t.addIssue({code:o.ZodIssueCode.custom,message:"ask_id must be a non-empty string",path:["askId"]}),e.dismiss===!0){(e.answers!==void 0||e.decline===!0||e.revise===!0)&&t.addIssue({code:o.ZodIssueCode.custom,message:"A dismissal carries no answers, decline or revise",path:["dismiss"]});return}e.reason!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"A reason applies to a dismissal",path:["reason"]}):e.decline!==!0&&!e.answers?t.addIssue({code:o.ZodIssueCode.custom,message:"A queued-ask answer needs answers or decline",path:["answers"]}):e.decline===!0&&e.answers!==void 0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either answers or decline",path:["decline"]}):e.revise===!0&&e.decline===!0?t.addIssue({code:o.ZodIssueCode.custom,message:"Supply either decline or revise",path:["revise"]}):e.answers!==void 0&&Object.keys(e.answers).length===0&&t.addIssue({code:o.ZodIssueCode.custom,message:"answers must name at least one question",path:["answers"]});return}e.epoch||t.addIssue({code:o.ZodIssueCode.custom,message:"An epoch is required to answer a gate",path:["epoch"]}),e.requestId||t.addIssue({code:o.ZodIssueCode.custom,message:"A request id is required to answer a gate",path:["requestId"]}),e.revise===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"revise applies to a queued ask",path:["revise"]}),e.dismiss===!0&&t.addIssue({code:o.ZodIssueCode.custom,message:"dismiss applies to a queued ask",path:["dismiss"]}),e.reason!==void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:"reason applies to a queued ask",path:["reason"]});return}if(e.op==="sessions.create"&&e.purpose===void 0){e.cwd===void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:"A conversation needs a working directory: only a configuration run (`purpose`) may omit `cwd`.",path:["cwd"]});return}if(e.op==="sessions.create"&&e.purpose!==void 0){for(const n of["cwd","target","model","draftId"])e[n]!==void 0&&t.addIssue({code:o.ZodIssueCode.custom,message:`A configuration run resolves its own \`${n}\`: send \`purpose\` alone.`,path:[n]});return}if(!(e.op!=="agent.publish"&&e.op!=="agent.republish"&&e.op!=="team.publish")){if((e.subscribe!==void 0||e.autoPush!==void 0||e.confirmPublicEgress!==void 0)&&!e.requestId){t.addIssue({code:o.ZodIssueCode.custom,message:"Initial link policy needs a durable publication request ID",path:["requestId"]});return}e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:o.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})}});const Je={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},ah={runtimeUnreachable:"runtime_unreachable"},fs="runtime_busy",kl="runtime_retiring";o.object({data:o.object({aside_id:o.string().optional(),status:o.union([o.enum(["adopted","queued"]),o.string()]).optional()}).passthrough()}).passthrough();const tk="aside_adopt_refused",ch=["session_closed","open_tool_batch","turn_running"];function nk(e){if(typeof e!="object"||e===null)return;const t=e.reason;return ch.find(n=>n===t)}const to={[Je.noCredential]:"This app is not paired with the running Local Operator server, so this control is unavailable.",[Je.refused]:"This app's credential for the running Local Operator server was refused, so this control is unavailable.",[Je.planeClosed]:"The running Local Operator server does not accept this app's desktop controls.",[Je.transportFailed]:"The Local Operator server did not answer this request."},vi={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 ps(e){return e!==void 0&&Object.values(Je).includes(e)}function lh(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return Je.refused;if(t===503)return Je.planeClosed}}const rk=o.object({step:o.string(),blocked_on:o.string(),configured:o.boolean(),ready:o.boolean(),verified:o.boolean(),url:o.string().nullable(),credential_id:o.number().int().positive().nullable(),identity_label:o.string().nullable(),credential_choices:o.array(o.object({id:o.number().int().positive(),identity_label:o.string().nullable().optional()}).passthrough()).default([]),quote:o.object({monthly_price_usd:o.string().nullable(),positive_balance:o.boolean(),eligible:o.boolean(),account_valid:o.boolean()}).passthrough().nullable(),receipts:o.array(o.object({step:o.string(),ok:o.boolean(),text:o.string()})).default([]),remedy:o.object({kind:o.string(),text:o.string(),command:o.string().nullable().optional(),url:o.string().nullable().optional()}).nullable(),source:o.string(),in_progress:o.boolean().default(!1),progress:o.array(o.string()).default([]),active_credential_id:o.number().int().positive().nullable().default(null),billing_outcome:o.string().optional(),reservation_outcome:o.string().optional(),failure_stage:o.string().optional()}).passthrough(),sk=new Set(["setup_in_progress","setup_deadline","setup_unavailable","setup_intent_corrupt"]),dh=88e4,uh=11e5,fh=2e4,ph=9e4,hh=new Set(["analytics.get","analytics.models","sessions.report"]),mh=new Set(["usage.get"]),gh=new Set(["networks.list","peers.list"]),yh=new Set([...hh,...mh,...gh]),_h=90,vh=30,bh=300,wh=10,Rl=15,Sh=1e4;function kh(e){const n=e.to==="local"||e.keep?bh:vh,r=Math.max(0,e.waitS??0);return(_h+n+wh+Rl)*1e3+r*1e3}const Rh=18e4,Eh=Rh+15e3,Ih=120,xh=135e3,Th=93e4,El=(Ih+30+Rl)*1e3,Ch=6e4,Ah=5*El,Oh=new Set(["hub.apply","hub.retry","hub.push","hub.skillPublish","hub.skillPull","hub.skillSubscribe","hub.skillUnpull","hub.check","hub.applyAll"]);function Ph(e){switch(e){case"hub.apply":case"hub.retry":case"hub.push":case"hub.skillPublish":case"hub.skillPull":case"hub.skillSubscribe":case"hub.skillUnpull":return El;case"hub.check":return Ch;case"hub.applyAll":return Ah;default:return null}}function jh(e){if(typeof e!="string"&&e.op==="sessions.transfer")return kh(e)+Sh;const t=typeof e=="string"?e:e.op;if(t==="approvals.approve")return Eh;if(t==="tunnel.setup.run")return Th;if(t==="tunnel.setup.plan")return xh;const n=Ph(t);return n!==null?n:yh.has(t)?ph:fh}const Mh=5e3;function Il(e){return jh(e)+Mh}const no="deadline_exceeded",xl="foreground_required",Tl="View these completions in the foreground before marking them read.",Dh=new Set(["capabilities","agent_messages.status","agent_messages.settings","agent_messages.allowlist.get","team_bridge.conversations.list","team_bridge.conversations.get","team_bridge.messages.list","team_bridge.messages.replies","team_bridge.unread","team_bridge.directory","team_bridge.status","accounts.list","analytics.get","analytics.models","approvals.list","commands.entities","commands.list","config.get","credentials.list","hub.updates","hub.links","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","projects.search","providers.list","quota.notice","runtimes.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.files","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.effective","teams.get","teams.list","tunnel.setup.plan","tunnel.setup.read","usage.get"]),Nh=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Lh(e,t){const n=Math.round(t/1e3),r=no;return e==="sessions.transfer"?{code:r,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.`}:e==="approvals.approve"?{code:r,message:`The app waits up to ${n} seconds for an approval, and the signing prompt was still open when it stopped waiting. The request was sent, so the decision may or may not have landed: read the approvals again — if the record still waits, answering it again is safe, because the store keeps the first decision and refuses a second.`}:Oh.has(e)?{code:r,message:"This is taking longer than expected. It may still finish; the mark will update."}:Dh.has(e)?{code:r,message:Nh.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:r,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 ik=dh,ok=uh;o.object({state:o.enum(["ok","depleted","limit_reached","unverified","unknown","not_applicable"]),provider:o.string(),kind:o.enum(["balance","subscription","radient","none"]),model_free:o.boolean(),title:o.string(),body:o.string(),actions:o.array(o.object({id:o.enum(["open_url","resend_verification","refresh"]),label:o.string(),url:o.string().nullable().optional()})),resets_at_ms:o.number().int().nullable().optional(),checked_at_ms:o.number().int(),age_ms:o.number().int().nullable().optional(),source:o.enum(["cached","live"])});function $h(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function Ba(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 Gs(e){return{...e.requestId?{request_id:e.requestId}:{},...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}}function Hs(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 Ga(e){return{sources:e.sources??null,session_ids:e.sessionIds??{},all:e.all??!1,include_subagents:e.includeSubagents??!1,include_cleared_segments:e.includeClearedSegments??!1,include_memory:e.includeMemory??!0,include_instructions:e.includeInstructions??!0,...e.maxSessions===void 0?{}:{max_sessions:e.maxSessions}}}function Ha(e){const t=new URLSearchParams;return e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id),t.size?`?${t.toString()}`:""}function Nr(e){return e===void 0?"":`?tenant_id=${encodeURIComponent(e)}`}function Uh(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"runtimes.list":return{path:"/v1/desktop/runtimes?probe=false",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"asks.list":return{path:"/v1/desktop/asks",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"approvals.list":return{path:"/v1/desktop/approvals",method:"GET"};case"approvals.approve":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/approve`,method:"POST"};case"approvals.deny":return{path:`/v1/desktop/approvals/${encodeURIComponent(e.approvalId)}/deny`,method:"POST"};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"imports.sources":return{path:"/v1/desktop/imports/sources",method:"GET"};case"imports.sessions":{const t=new URLSearchParams({source:e.source});return e.includeSubagents&&t.set("include_subagents","true"),{path:`/v1/desktop/imports/sessions?${t.toString()}`,method:"GET"}}case"imports.preview":return{path:"/v1/desktop/imports/preview",method:"POST",body:Ga(e)};case"imports.start":return{path:"/v1/desktop/imports/jobs",method:"POST",body:Ga(e)};case"imports.status":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"GET"};case"imports.cancel":return{path:`/v1/desktop/imports/jobs/${encodeURIComponent(e.jobId)}`,method:"DELETE"};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,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};case"hub.updates":return{path:"/v1/desktop/hub/updates",method:"GET"};case"hub.skillPull":return{path:"/v1/desktop/hub/skills/pull",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.skillSubscribe":return{path:"/v1/desktop/hub/skills/subscribe",method:"POST",body:{request_id:e.requestId,hub_id:e.hubId,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId,local_alias:e.localAlias}};case"hub.skillUnpull":return{path:"/v1/desktop/hub/skills/unpull",method:"POST",body:{request_id:e.requestId,link_id:e.linkId}};case"hub.skillPublish":return{path:"/v1/desktop/hub/skills/publish",method:"POST",body:{request_id:e.requestId,dry_run:e.dryRun,source_skill:e.sourceSkill,local_alias:e.localAlias,visibility:e.visibility,tenant_id:e.tenantId,subscribe:e.subscribe,auto_push:e.autoPush,confirm_public_egress:e.confirmPublicEgress,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};case"hub.links":return{path:`/v1/desktop/hub/links${e.kind?`?kind=${e.kind}`:""}`,method:"GET"};case"hub.policy":return{path:`/v1/desktop/hub/links/${encodeURIComponent(e.linkId)}`,method:"PATCH",body:{request_id:e.requestId,expected_policy_revision:e.expectedPolicyRevision,...e.subscribe!==void 0?{subscribe:e.subscribe}:{},...e.autoPush!==void 0?{auto_push:e.autoPush}:{},...e.confirmPublicEgress!==void 0?{confirm_public_egress:e.confirmPublicEgress}:{}}};case"hub.check":return{path:"/v1/desktop/hub/updates/check",method:"POST",body:{request_id:e.requestId,...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};case"hub.apply":return{path:"/v1/desktop/hub/updates/apply",method:"POST",body:{request_id:e.requestId,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmApply?{confirm_apply:!0}:{},...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{},...e.prefer?{prefer:e.prefer}:{},...e.acknowledgeUnknownBaseline!==void 0?{acknowledge_unknown_baseline:e.acknowledgeUnknownBaseline}:{},...e.dryRun!==void 0?{dry_run:e.dryRun}:{},...e.resolveSource===!0?{resolve_source:!0,hub_source:e.hubSource,visibility:e.visibility,tenant_id:e.tenantId??null}:{}}};case"hub.applyAll":return{path:"/v1/desktop/hub/updates/apply-all",method:"POST",body:{request_id:e.requestId,...e.kind?{kind:e.kind}:{}}};case"hub.retry":return{path:"/v1/desktop/hub/updates/retry",method:"POST",body:{request_id:e.requestId,...e.linkId?{link_id:e.linkId}:{},...e.direction?{direction:e.direction}:{},...e.kind?{kind:e.kind}:{},...e.name?{name:e.name}:{}}};case"hub.push":return{path:"/v1/desktop/hub/updates/push",method:"POST",body:{request_id:e.requestId,link_id:e.linkId,direction:e.direction,dry_run:e.dryRun,...e.previewReceipt?{preview_receipt:e.previewReceipt}:{},...e.confirmPublish?{confirm_publish:!0}:{}}};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.effective":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}/effective`,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,...e.expectedDefinitionRevision!==void 0&&e.expectedDefinitionRevision!==null?{expected_definition_revision:e.expectedDefinitionRevision}:{}}};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"),e.sort&&t.set("sort",e.sort),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"delegated_cleanup_notice.ack":return{path:"/v1/desktop/delegated-cleanup-notice/ack",method:"POST"};case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??kp)});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,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.peer?{peer:e.peer}:{},...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{},...e.purpose?{purpose:e.purpose}:{}}};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":{const t=new URLSearchParams;return e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),es(t,`/v1/desktop/sessions/${e.sessionId}`,e.orderIds??[])),{path:`/v1/desktop/sessions/${e.sessionId}${t.size?`?${t}`:""}`,method:"GET"}}case"sessions.files":{const t=new URLSearchParams({limit:String(e.limit??200)});for(const n of["scope","kind","q","sort","order","cursor"]){const r=e[n];r!==void 0&&t.set(n,r)}return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files?${t}`,method:"GET"}}case"sessions.files.materialise":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/files/${encodeURIComponent(e.fileId)}/materialise`,method:"POST"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),e.openFrame&&(t.set("open_frame","1"),t.set("supplements","1")),e.journalOrder&&(t.set("journal_order","1"),e.peerJournalSource&&t.set("peer_journal_source","1"),e.sourceRead==="metadata"?t.set("source_read","metadata"):e.sourceRead==="payload"&&e.expectedJournalGeneration&&t.set("source_read","payload"),e.expectedJournalGeneration&&t.set("expected_journal_generation",e.expectedJournalGeneration),es(t,`/v1/desktop/sessions/${e.sessionId}/history`,e.orderIds??[])),{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??Ep)});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??[],...e.files?.length?{files:e.files}:{},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 e.askId!==void 0?{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{ask_id:e.askId,answers:e.answers,decline:e.decline,...e.revise===!0?{revise:!0}:{},...e.dismiss===!0?{dismiss:!0,...e.reason!==void 0?{reason:e.reason}:{}}:{}}}:{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"tags.list":return{path:"/v1/desktop/tags",method:"GET"};case"tags.replace":return{path:"/v1/desktop/tags",method:"PUT",body:{tags:e.tags}};case"sessions.tags":return{path:`/v1/desktop/sessions/${e.sessionId}/tags`,method:"PUT",body:{tags:e.tags,primary:e.primary,...e.expected_revision===void 0?{}:{expected_revision:e.expected_revision}}};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"supplements.cancel":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/cancel`,method:"POST",body:{anchor:e.anchor}};case"supplements.restart":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/restart`,method:"POST",body:{anchor:e.anchor}};case"supplements.steer":return{path:`/v1/desktop/sessions/${e.sessionId}/supplements/${e.job}/steer`,method:"POST",body:{anchor:e.anchor,text:e.text}};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":{Hs(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??{},...Gs(e)}}}case"agent.republish":{Hs(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??{},...Gs(e),...e.expectedRemoteRevision?{expected_remote_revision:e.expectedRemoteRevision}:{}}}}case"team.publish":{Hs(e);const t=new URLSearchParams;return e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId)),{path:`/v1/teams/${e.teamId}/publish${t.size?`?${t}`:""}`,method:"POST",body:Gs(e)}}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,...$h(e),message:e.message,...Ba(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...Ba(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"monitors.cancel":return{path:`/v1/desktop/monitors/${encodeURIComponent(e.sessionId)}/${encodeURIComponent(e.monitorId)}`,method:"DELETE"};case"jobs.cancel":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/jobs/${encodeURIComponent(e.jobId)}/cancel`,method:"POST"};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":{const t=e.scope?`&scope=${e.scope}`:"";return{path:`/v1/desktop/models?live=${e.live??!1}${t}`,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"quota.notice":{const t=new URLSearchParams({refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),{path:`/v1/desktop/quota-notice?${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":{const t=new URLSearchParams;e.sessionId&&t.set("session_id",e.sessionId),e.cwd&&t.set("cwd",e.cwd),e.name&&t.set("name",e.name);const n=t.toString();return{path:`/v1/desktop/skills${n?`?${n}`:""}`,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,entry_id:e.entryId,auto_tag:e.autoTag}};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"tunnel.setup.read":return{path:e.credentialId===void 0?"/v1/desktop/tunnel/setup":`/v1/desktop/tunnel/setup?credential_id=${e.credentialId}`,method:"GET"};case"tunnel.setup.plan":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"plan",...e.credentialId!==void 0?{credential_id:e.credentialId}:{}}};case"tunnel.setup.run":return{path:"/v1/desktop/tunnel/setup",method:"POST",body:{action:"run",credential_id:e.credentialId,...e.acceptMonthlyPrice!==void 0?{accept_monthly_price:e.acceptMonthlyPrice}:{}}};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"agent_messages.status":return{path:`/v1/desktop/team-bridge/status?boundary=${e.boundary}`,method:"GET"};case"agent_messages.enable":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,tenant_id:e.tenant_id,state:e.state,consent_version:e.consent_version,consented_via:e.consented_via}};case"agent_messages.settings":return{path:`/v1/desktop/team-bridge/settings${Nr(e.tenant_id)}`,method:"GET"};case"agent_messages.settings.put":return{path:"/v1/desktop/team-bridge/settings",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},...e.consent_version===void 0?{}:{consent_version:e.consent_version},...e.consented_via===void 0?{}:{consented_via:e.consented_via},...e.label===void 0?{}:{label:e.label},state:e.state}};case"agent_messages.allowlist.get":return{path:`/v1/desktop/team-bridge/allowlist${Nr(e.tenant_id)}`,method:"GET"};case"agent_messages.allowlist.put":return{path:"/v1/desktop/team-bridge/allowlist",method:"PUT",body:{expected_account_id:e.expected_account_id,...e.tenant_id===void 0?{}:{tenant_id:e.tenant_id},entries:e.entries}};case"team_bridge.conversations.list":{const t=new URLSearchParams;return e.scope==="account"&&t.set("scope","account"),e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor),e.before&&t.set("before",e.before),{path:`/v1/desktop/team-bridge/conversations${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.conversations.get":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}${Nr(e.tenant_id)}`,method:"GET"};case"team_bridge.conversations.create":return{path:"/v1/desktop/team-bridge/conversations",method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},kind:e.kind,...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agent_capable===void 0?{}:{agent_capable:e.agent_capable},members:e.members}};case"team_bridge.conversations.lifecycle":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/${e.action}${e.action==="join"?"":Ha(e)}`,method:"POST",...e.action==="join"&&(e.tenant_id||e.expected_account_id)?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.join":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/join`,method:"POST",...e.tenant_id||e.expected_account_id?{body:{...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.expected_account_id?{expected_account_id:e.expected_account_id}:{}}}:{}};case"team_bridge.conversations.notify":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},notify:e.notify}};case"team_bridge.conversations.members.add":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.expected_account_id&&t.set("expected_account_id",e.expected_account_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members${n}`,method:"POST",body:e.members}}case"team_bridge.conversations.members.remove":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}${Ha(e)}`,method:"DELETE"};case"team_bridge.conversations.consent":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/members/${encodeURIComponent(e.account_id)}/consent`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},decision:e.decision,consent_version:e.consent_version}};case"team_bridge.messages.list":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.before_seq!==void 0&&t.set("before_seq",String(e.before_seq)),e.endpoint_id&&t.set("endpoint_id",e.endpoint_id);const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages${n}`,method:"GET"}}case"team_bridge.reactions.toggle":{const t=`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/reactions/${encodeURIComponent(e.emoji)}`;return e.active?{path:t,method:"PUT",body:e.tenant_id?{tenant_id:e.tenant_id}:{}}:{path:`${t}${Nr(e.tenant_id)}`,method:"DELETE"}}case"team_bridge.messages.send":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},client_ref:e.client_ref,body:e.body,...e.agent_label?{agent_label:e.agent_label}:{},...e.thread_root_id?{thread_root_id:e.thread_root_id}:{}}};case"team_bridge.messages.replies":{const t=new URLSearchParams;e.tenant_id&&t.set("tenant_id",e.tenant_id),e.limit!==void 0&&t.set("limit",String(e.limit)),e.after_seq!==void 0&&t.set("after_seq",String(e.after_seq));const n=t.size>0?`?${t.toString()}`:"";return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/messages/${encodeURIComponent(e.message_id)}/replies${n}`,method:"GET"}}case"team_bridge.read":return{path:`/v1/desktop/team-bridge/conversations/${encodeURIComponent(e.conversation_id)}/read`,method:"POST",body:{...e.expected_account_id?{expected_account_id:e.expected_account_id}:{},...e.tenant_id?{tenant_id:e.tenant_id}:{},...e.seq===void 0?{}:{seq:e.seq},...e.muted===void 0?{}:{muted:e.muted}}};case"team_bridge.unread":{const t=new URLSearchParams;return e.scope==="account"?t.set("scope","account"):e.tenant_id&&t.set("tenant_id",e.tenant_id),{path:`/v1/desktop/team-bridge/unread${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}case"team_bridge.directory":return{path:`/v1/desktop/team-bridge/directory?tenant_id=${encodeURIComponent(e.tenant_id)}`,method:"GET"};case"team_bridge.status":{const t=new URLSearchParams;return e.boundary&&t.set("boundary",e.boundary),{path:`/v1/desktop/team-bridge/status${t.size>0?`?${t.toString()}`:""}`,method:"GET"}}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"tts.paths":return{path:"/v1/tts/paths",method:"GET"};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"library.list":{const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.q&&t.set("q",e.q),e.category&&t.set("category",e.category),e.kind&&t.set("kind",e.kind),e.origin_group&&t.set("origin_group",e.origin_group),e.origin&&t.set("origin",e.origin),e.tag&&t.set("tag",e.tag),e.tag_mode&&t.set("tag_mode",e.tag_mode),e.highlighted!==void 0&&t.set("highlighted",e.highlighted?"1":"0"),e.organized!==void 0&&t.set("organized",e.organized?"1":"0"),e.favorite!==void 0&&t.set("favorite",e.favorite?"1":"0"),e.session&&t.set("session",e.session),e.session_id&&t.set("session_id",e.session_id),e.sort&&t.set("sort",e.sort),e.order&&t.set("order",e.order),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);const n=t.toString();return{path:`/v1/desktop/library/assets${n?`?${n}`:""}`,method:"GET"}}case"library.get":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"GET"};case"library.update":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}`,method:"PATCH",body:e.fields};case"library.tags":return{path:"/v1/desktop/library/tags",method:"GET"};case"library.tags.create":return{path:"/v1/desktop/library/tags",method:"POST",body:{name:e.name,...e.category!==void 0?{category:e.category}:{}}};case"library.tags.update":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"PATCH",body:{...e.name!==void 0?{name:e.name}:{},...e.category!==void 0?{category:e.category}:{}}};case"library.tags.delete":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}`,method:"DELETE"};case"library.tags.merge":return{path:`/v1/desktop/library/tags/${encodeURIComponent(e.id)}/merge`,method:"POST",body:{into:e.into}};case"library.tags.assign":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/tags`,method:"PUT",body:{tags:e.tags,...e.primary!==void 0?{primary:e.primary}:{}}};case"library.chat.link":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"PUT",body:{session_id:e.sessionId}};case"library.chat.clear":return{path:`/v1/desktop/library/assets/${encodeURIComponent(e.id)}/chat`,method:"DELETE"};case"library.librarian":{const t=e.action??"status";return t==="status"?{path:"/v1/desktop/librarian",method:"GET"}:{path:"/v1/desktop/librarian",method:"POST",body:{op:t}}}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,...e.force_done===!0?{force_done:!0}:{}}};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"projects.request_update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/request-update`,method:"POST"};case"projects.search":return{path:`/v1/desktop/projects/search?${new URLSearchParams({q:e.q,limit:String(e.limit??nh)})}`,method:"GET"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}};case"code_requests.list":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests`,method:"GET"};case"code_requests.refresh":return{path:`/v1/desktop/sessions/${e.sessionId}/code-requests/refresh`,method:"POST",body:{...e.keys!==void 0?{keys:e.keys}:{},...e.force!==void 0?{force:e.force}:{}}};case"static.sign":return{path:"/v1/static/sign",method:"POST",body:{route:e.route,path:e.path,ttl_s:e.ttlS}};case"sidebar_layout.get":return{path:"/v1/desktop/sidebar-layout",method:"GET"};case"sidebar_layout.set":return{path:"/v1/desktop/sidebar-layout",method:"PUT",body:{layout:e.layout}}}}const ak=64,ck=64*1024*1024,lk="superseded_completion_token",dk="store_busy",Fh="session_is_remote",Bh="owner_build_behind";function uk(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function mn(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=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 Gh(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const fk=e=>typeof e?.goal_status=="string",pk=e=>(e?.goal??"").trim().length>0;function Hh(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 Zn={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."},Wa={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},Wh={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},zh={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},Zh={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},Vh={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function za(e){return e?e===Zn.notPaired?zh:e===Zn.serverDown?Wh:e===Zn.frameBudget?Vh:Wa:Wa}const Za=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const p=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(h=>h(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d))},l=t=e(r,s,c);return c},Kh=e=>e?Za(e):Za,Yh=e=>e;function Qh(e,t=Yh){const n=aa.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return aa.useDebugValue(n),n}const Va=e=>{const t=Kh(e),n=r=>Qh(t,r);return Object.assign(n,t),n},vr=e=>e?Va(e):Va;function Cl(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const a=l=>l===null?null:JSON.parse(l,void 0),c=(i=n.getItem(s))!=null?i:null;return c instanceof Promise?c.then(a):a(c)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const bi=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return bi(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return bi(r)(n)}}}},Jh=(e,t)=>(n,r,s)=>{let i={storage:Cl(()=>localStorage),partialize:m=>m,version:0,merge:(m,y)=>({...y,...m}),...t},a=!1;const c=new Set,l=new Set;let d=i.storage;if(!d)return e((...m)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...m)},r,s);const u=()=>{const m=i.partialize({...r()});return d.setItem(i.name,{state:m,version:i.version})},f=s.setState;s.setState=(m,y)=>{f(m,y),u()};const p=e((...m)=>{n(...m),u()},r,s);s.getInitialState=()=>p;let h;const g=()=>{var m,y;if(!d)return;a=!1,c.forEach(b=>{var R;return b((R=r())!=null?R:p)});const _=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(m=r())!=null?m:p))||void 0;return bi(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate){const R=i.migrate(b.state,b.version);return R instanceof Promise?R.then(M=>[!0,M]):[!0,R]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,b.state];return[!1,void 0]}).then(b=>{var R;const[M,G]=b;if(h=i.merge(G,(R=r())!=null?R:p),n(h,!0),M)return u()}).then(()=>{_?.(h,void 0),h=r(),a=!0,l.forEach(b=>b(h))}).catch(b=>{_?.(void 0,b)})};return s.persist={setOptions:m=>{i={...i,...m},m.storage&&(d=m.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>a,onHydrate:m=>(c.add(m),()=>{c.delete(m)}),onFinishHydration:m=>(l.add(m),()=>{l.delete(m)})},i.skipHydration||g(),h||p},hs=Jh,Xh=(e,t)=>e!==null&&e.message===t.message&&e.removed===t.removed&&e.max_age_hours===t.max_age_hours&&e.in_progress===t.in_progress&&e.first_removal_at===t.first_removal_at&&e.freed_bytes_estimate===t.freed_bytes_estimate&&e.record===t.record;function qh(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.message!="string"||t.message.trim()==="")return null;const n=(r,s)=>typeof r=="number"&&Number.isFinite(r)?r:s;return{message:t.message,removed:n(t.removed,0),max_age_hours:n(t.max_age_hours,48),in_progress:t.in_progress===!0,first_removal_at:typeof t.first_removal_at=="string"?t.first_removal_at:"",freed_bytes_estimate:typeof t.freed_bytes_estimate=="number"&&Number.isFinite(t.freed_bytes_estimate)?t.freed_bytes_estimate:null,record:typeof t.record=="string"?t.record:""}}const Al=vr()(hs(e=>({notice:null,receive:t=>e(n=>Xh(n.notice,t)?n:{notice:t}),dismiss:()=>e(t=>t.notice===null?t:{notice:null})}),{name:"delegated-cleanup-notice",storage:Cl(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({notice:e.notice})}));async function Ol(e){if(window.api?.desktop)try{return await em(window.api.desktop.request(e),e)}catch(n){throw n instanceof ye?n:om(n)?new $t(Tl,xl):new ye(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 ye(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new ye(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function em(e,t){const n=Il(t);let r;return Promise.race([e,new Promise((s,i)=>{r=setTimeout(()=>{const a=Lh(t.op,n);i(new ye(null,a.message,void 0,a.code))},n)})]).finally(()=>clearTimeout(r))}const tm="This server did not answer the request for its desktop controls.";class ye extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,s,i,a){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=s,this.retryAfterMs=i,this.detail=a}}class $t extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function ro(e,t){return e instanceof ye||e instanceof $t?ps(e.code)?to[e.code]:e.message:t}function nm(e,t,n,r){return typeof r=="string"?r:n===vi.noCredential?Je.noCredential:n===vi.transportFailed?Je.transportFailed:lh(Uh(e).path,t)}async function xe(e){const t=await Ol(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new ye(t.status,r??tm,void 0,nm(e,t.status,r,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,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&rm(n?.result),n?.result}function rm(e){if(typeof e!="object"||e===null)return;const t=qh(e.delegated_cleanup_notice);t&&Al.getState().receive(t)}async function sm(){try{await xe({op:"delegated_cleanup_notice.ack"})}catch{}}async function hk(){Al.getState().dismiss(),await sm()}function im(e){return e instanceof ye&&e.code===no}function mk(e){if(!(e instanceof ye))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===Bh:e.code===Fh}function gk(e){return e instanceof $t&&e.code===xl}function om(e){return e instanceof Error&&e.message.includes(Tl)}async function yk(e){const t=await Ol(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function _k(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await xe({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function am(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),es(r,"/__desktop/stream",e.orderIds??[]));const s=new EventSource(`/__desktop/stream?${r}`);return s.onmessage=i=>{t({kind:"data",data:i.data})},s.onerror=()=>{s.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Zn.ended}),s.close())},()=>{s.close(),t({kind:"end"})}}async function vk(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=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}),s=r.headers.get("content-type")??"";if(!r.ok){let i="The media request failed.",a;if(s.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")i=l;else if(typeof l=="object"&&l!==null){const d=l;typeof d.text=="string"&&d.text.trim()?i=d.text:typeof d.message=="string"&&d.message.trim()&&(i=d.message),typeof d.code=="string"&&(a=d.code)}}catch{}return{status:r.status,kind:"error",detail:i,code:a!==void 0&&ps(a)?a:i===vi.noCredential?Je.noCredential:void 0}}return s.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:s||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function bk(e){return e.kind==="error"?ps(e.code)?new $t(to[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const Nn=e=>{const t=e.id;return typeof t=="string"?t:typeof t=="number"?String(t):null};function cm(e,t){const n=new Set((t.removed??[]).map(String)),r=e.filter(a=>{const c=Nn(a);return c===null||!n.has(c)});for(const a of t.upserted??[]){const c=Nn(a);if(c===null){r.push(a);continue}const l=r.findIndex(d=>Nn(d)===c);l===-1?r.push(a):r[l]=a}if(!t.order)return r;const s=new Map;for(const a of r){const c=Nn(a);c!==null&&s.set(c,a)}const i=[];for(const a of t.order){const c=String(a),l=s.get(c);l&&(i.push(l),s.delete(c))}for(const a of r){const c=Nn(a);c!==null&&s.has(c)?(i.push(a),s.delete(c)):c===null&&i.push(a)}return i}const wi=e=>({revision:Ye(e),demand:e.orderDemand}),Kt=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Rn(e,t,n,r,s,i={}){let a=e;const c=t.journal_generation;if(t.reconcile===!0){const p=typeof c=="string"&&c.length>0?c:void 0;return a.orderNeedsReconcile&&a.orderWantedGeneration===p?a.journalMode?a:{...a,journalMode:!0}:{...a,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:p,orderDemand:p!==void 0?{generation:p}:{}}}if(typeof c!="string"||c.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!a.journalMode?{...a,journalMode:!0}:a;if(r&&t.journal_order_state==="ready"&&s&&a.orderNeedsReconcile&&a.orderDemand===s.demand&&(a={...a,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),c!==a.journalGeneration&&!r)return a.orderNeedsReconcile&&a.orderWantedGeneration===c?a:{...a,orderNeedsReconcile:!0,orderWantedGeneration:c,orderDemand:{generation:c}};let l=a.journalMode?a:{...a,journalMode:!0};if(c!==a.journalGeneration&&(l={...a,journalMode:!0,journalGeneration:c,orderRevision:(a.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:a.orderNeedsReconcile,orderWantedGeneration:a.orderWantedGeneration,orderDemand:a.orderDemand},i.peer===!0)){const p=(a.orderRevision??0)+1,h=new Map;for(const g of a.records){const m=g.sourceEntryId??(g.kind==="tool"||g.kind==="supplement"?null:g.id);typeof m=="string"&&m.length>0&&m.length<=128&&h.set(m,p)}l={...l,...h.size>0?{journalBodyOwed:h}:{},journalSourceVoid:void 0}}let d=l.journalPositions??new Map;const u=d,f=(p,h,g)=>{if(!Kt(g))return;const m=d.get(p);m&&m.seq>=g||(d===u&&(d=new Map(d)),d.set(p,{entryId:h,seq:g}))};for(const[p,h]of Object.entries(t.journal_ordinals??{}))f(p,p,h);for(const p of n)typeof p.id=="string"&&(f(p.id,p.id,p.journal_seq),p.role==="tool"&&typeof p.tool_call_id=="string"&&f(`tool:${p.tool_call_id}`,p.id,p.journal_seq),typeof p.anchor=="string"&&f(`supplement:${p.anchor}`,p.id,p.journal_seq));return d!==u&&(l={...l,journalPositions:d}),l}function so(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const s=n,i=r;return t.tool_calls.forEach((a,c)=>{!a||typeof a.id!="string"||(n.get(a.id)!==t.id&&(n===s&&(n=new Map(n)),n.set(a.id,t.id)),r.get(a.id)!==c&&(r===i&&(r=new Map(r)),r.set(a.id,c)))}),n===s&&r===i?e:{...e,journalCallOwners:n,journalCallSlots:r}}function Pl(e,t){const n=new Set(e.map(i=>i.id));let r=!1,s;for(let i=0;i<e.length;i++){const a=e[i];if(a.kind==="user"&&a.provisional===!0){s=a;continue}!t(a)&&s&&(a.sourceAdmissionAnchor===void 0||!n.has(a.sourceAdmissionAnchor))&&(e[i]={...a,sourceAdmissionAnchor:s.id},r=!0),s=e[i]}return r}function jl(e,t,n,r,s){const i=[],a=new Set;let c=e,l;for(;c!==void 0;){if(s.has(c.id)){l=s.get(c.id);break}if(n(c)){l=r(c);break}if(c.kind==="user"&&c.provisional===!0||a.has(c.id))break;a.add(c.id),i.push(c.id),c=c.sourceAdmissionAnchor?t.get(c.sourceAdmissionAnchor):void 0}for(const d of i)s.set(d,l);return l}function Ml(e,t){const n=new Map;return r=>{if(!r)return;const s=t(r);if(s===void 0)return;const i=[],a=new Set;let c=r,l=!0;for(;c;){if(n.has(c.id)){l=n.get(c.id)===!0;break}if(a.has(c.id)||t(c)===void 0){l=!1;break}a.add(c.id),i.push(c.id),c=c.sourceAdmissionAnchor===void 0?void 0:e.get(c.sourceAdmissionAnchor)}for(const d of i)n.set(d,l);return l?s:void 0}}function ts(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const s=new Map;t.forEach((a,c)=>{if(a.kind!=="tool")return;const l=n.get(a.toolCallId);if(l===void 0||!r.has(a.toolCallId))return;const d=s.get(l);d?d.push(c):s.set(l,[c])});let i=t;for(const a of s.values()){if(a.length<2)continue;const c=a.map(l=>t[l]).sort((l,d)=>(r.get(l.toolCallId)??0)-(r.get(d.toolCallId)??0));c.every((l,d)=>l===t[a[d]])||(i===t&&(i=t.slice()),a.forEach((l,d)=>{i[l]=c[d]}))}return i}function Dl(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return lm(e,t);const n=e.journalGeneration,r=e.journalPositions;let s=!1;const i=t.map(h=>{let m=[r?.get(h.sourceEntryId??h.id),r?.get(h.id)].filter(b=>b!==void 0).sort((b,R)=>R.seq-b.seq)[0];if(h.journalGeneration===n&&Kt(h.journalSeq)&&(!m||h.journalSeq>m.seq)&&(m={entryId:h.sourceEntryId??h.id,seq:h.journalSeq}),!m||!n||!(h.kind==="user"&&(h.provisional===!0||h.local===!0))&&h.sourceEntryId===m.entryId&&h.journalSeq===m.seq&&h.journalGeneration===n)return h;s=!0;let _={...h,sourceEntryId:m.entryId,journalSeq:m.seq,journalGeneration:n};if(_.kind==="user"){const{provisional:b,local:R,...M}=_;_=M}return _});Pl(i,h=>h.journalGeneration===n&&Kt(h.journalSeq))&&(s=!0);const c=new Map,l=new Map(i.map(h=>[h.id,h])),d=Ml(l,h=>h!==void 0&&h.journalGeneration===n&&Kt(h.journalSeq)?h.journalSeq:void 0),u=h=>d(h)!==void 0,f=(h,g)=>{const m=d(h);if(h.kind==="user"&&h.provisional===!0&&m===void 0)return[1,0,0,0,g];const y=h.kind==="supplement"?h.anchor:h.kind==="tool"?e.journalCallOwners?.get(h.toolCallId)??e.argsByCall.get(h.toolCallId)?.anchorId:void 0,_=typeof y=="string"?d(l.get(y)):void 0,b=m===void 0?jl(h,l,u,d,c):void 0,R=_??m??b;return R===void 0?[1,0,0,0,g]:[0,R,_!==void 0?1:m!==void 0?0:2,m??Number.MAX_SAFE_INTEGER,g]},p=i.map((h,g)=>({record:h,index:g,rank:f(h,g)}));return p.sort((h,g)=>{for(let m=0;m<h.rank.length;m++){const y=h.rank[m]-g.rank[m];if(y)return y}return 0}),!s&&p.every((h,g)=>h.index===g)?ts(e,t):ts(e,p.map(h=>h.record))}function lm(e,t){const n=e.journalGeneration,r=e.journalPositions,s=new Map;for(const m of t){let _=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(b=>b!==void 0).sort((b,R)=>R.seq-b.seq)[0];m.journalGeneration===n&&Kt(m.journalSeq)&&(!_||m.journalSeq>_.seq)&&(_={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),_&&s.set(m.id,_)}const i=m=>m===void 0?void 0:s.get(m.id)??r?.get(m.sourceEntryId??m.id)??r?.get(m.id);let a=!1;const c=t.slice();Pl(c,m=>m.journalGeneration===n&&Kt(m.journalSeq))&&(a=!0);const d=new Map,u=new Map(c.map(m=>[m.id,m])),f=Ml(u,m=>i(m)?.seq),p=m=>f(m)!==void 0,h=(m,y)=>{const _=f(m);if(m.kind==="user"&&m.provisional===!0&&_===void 0)return[1,0,0,0,y];const b=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,R=typeof b=="string"?f(u.get(b)):void 0,M=_===void 0?jl(m,u,p,f,d):void 0,G=R??_??M;return G===void 0?[1,0,0,0,y]:[0,G,R!==void 0?1:_!==void 0?0:2,_??Number.MAX_SAFE_INTEGER,y]},g=c.map((m,y)=>({record:m,index:y,rank:h(m,y)}));return g.sort((m,y)=>{for(let _=0;_<m.rank.length;_++){const b=m.rank[_]-y.rank[_];if(b)return b}return 0}),!a&&g.every((m,y)=>m.index===y)?ts(e,t):ts(e,g.map(m=>m.record))}function ut(e){const t=e.records.filter(s=>s.kind==="user"&&s.provisional===!0),n=e.records.filter(s=>s.journalGeneration!==e.journalGeneration||!Kt(s.journalSeq)),r=[...t,...n].map(s=>s.sourceEntryId??(s.kind==="tool"||s.kind==="supplement"?null:s.id));if(r.push(...io(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let s=r.length-1;s>=0;s--){const i=r[s];typeof i=="string"&&e.journalSourceVoid.has(i)&&r.splice(s,1)}return[...new Set(r.filter(s=>typeof s=="string"&&s.length>0&&s.length<=128))]}function io(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s=="string"&&s.length>0&&s.length<=128&&t.add(s)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function Nl(e,t){const n=e.journalPositions;return ut(e).filter(r=>!n?.has(r)&&!t?.has(r))}const Ye=e=>e.orderRevision??0;async function dm(e){const t=new Map,n=c=>{let l=t.get(c);return l||(l=new Set,t.set(c,l)),l},r=(c,l)=>l==="payload"?io(c):l==="lookup"?Nl(c):ut(c);let s=e.getTranscript().journalGeneration,i=0,a=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const c=e.getTranscript(),l=wi(c),d=l.revision,u=e.sweep?.(c,n);if(u?.kind==="none")return{kind:"complete",transcript:c};const f=u?.kind??"authority",p=yp(r(c,f).filter(y=>!n(f).has(y)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),h=await e.read(p,f);if(!e.isCurrent()||Ye(e.getTranscript())!==d)return{kind:"stale"};if(e.commit(h,d,l),!e.isCurrent())return{kind:"stale"};const g=e.getTranscript(),m=e.page(h);if(m.journal_order_state==="ready"&&m.journal_generation===g.journalGeneration){m.journal_generation!==s&&(t.clear(),s=m.journal_generation);for(const b of p)n(f).add(b);if(g.orderNeedsReconcile){if(g.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear();continue}if(f==="payload"){const b=(m.source_retry_ids??[]).filter(R=>typeof R=="string"&&R.length>0&&R.length<=128);if(b.length>0&&p.length>1&&a===0){a++;for(const R of b)n("payload").delete(R);continue}}const y=e.sweep?.(g,n);if(y?.kind==="none")return{kind:"complete",transcript:g};const _=y?.kind??"authority";if(r(g,_).some(b=>!n(_).has(b)))continue;return{kind:"complete",transcript:g}}if(!g.orderNeedsReconcile||g.orderDemand===l.demand||i===1)return{kind:"waiting"};i++,t.clear()}}function rt(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const s=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof s=="string"&&s?s:e.id}function Ws(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function Ka(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function wk(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const i of t){if(!i.settled||typeof i.run_key!="string"||i.run_key.length===0)continue;const a=Ws(i.action_count);if(a===null)continue;const c={actions:a,workedSeconds:Ka(i.worked_seconds),failed:Ws(i.failed_count)??0,complete:i.complete!==!1,openingUserId:typeof i.opening_user_id=="string"&&i.opening_user_id.length>0?i.opening_user_id:null,closingAnswerId:typeof i.closing_answer_id=="string"&&i.closing_answer_id.length>0?i.closing_answer_id:null,crossSessionActions:Ws(i.cross_session_action_count),crossSessionWorkedSeconds:Ka(i.cross_session_worked_seconds)};n.set(i.run_key,c),c.openingUserId!==null&&n.set(c.openingUserId,c),c.closingAnswerId!==null&&n.set(c.closingAnswerId,c)}if(n.size===0)return null;const r=new Set;for(const i of e.entries)r.add(rt(i));const s=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:s?rt(s):null}}}function um(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(i=>i.opening_user_id===n.id))return null;const s=Math.round((n.ts??0)*1e3);return s>0?{id:n.id,tsMs:s}:null}function fm(e,t,n){const r=um(e),s=e?.entries;if(r===null||!s||s.length===0)return!1;const i=Math.round((s[s.length-1].ts??0)*1e3);if(!(i>r.tsMs))return!1;for(const[a,c]of t)if(!n.has(a)&&(c===null||!(c>r.tsMs)||!(c<i)))return!1;return!0}const oo=new Set,en="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Ll=new RegExp(`[${en}]`),Sk=new RegExp(`[${en}]+`),kk=new RegExp(`[${en}]+`,"g"),pm=new RegExp(`^[${en}]+|[${en}]+$`,"g"),hm=new RegExp(`^[${en}]+`),Rk=new RegExp(`[^${en}]`);function Ot(e){return e.replace(pm,"")}function lr(e){return e.replace(hm,"")}function mm(e,t){return t===0||Ll.test(e[t-1])}function $l(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&mm(e,n)&&t.push(n);return t}function ao(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
|
|
2
2
|
`,n-1)+1,s=e.indexOf(`
|
|
3
|
-
`,n),i=s===-1?e.length:s;let a=e.slice(r,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function gm(e,t){if(t.size===0)return null;for(const n of $l(e)){const r=e.slice(n+1),s=r.indexOf(" ");if(s!==-1&&t.has(r.slice(0,s).toLowerCase()))return n}return null}function co(e,t,n){const r=gm(e,n);let s=null;for(const i of $l(e)){if(i===r)return t>i?i:s;i<=t&&(s=i)}return s}function ym(e,t=null,n=oo){const{line:r,lineStart:s,column:i}=ao(e,t),a=co(r,i,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Ll.test(r[c]);)c++;return i>c?null:{start:s+a,query:r.slice(a+1,c),end:s+c}}function
|
|
4
|
-
`.includes(e[c]);return r===""?s>0&&a(s-1)?s-=1:a(i)&&(i+=1):s===0&&a(i)&&(i+=1),{text:`${e.slice(0,s)}${r}${e.slice(i)}`,caret:s+r.length}}const vm=/^\$([A-Za-z0-9][A-Za-z0-9._-]*)/,bm=/<skill name="([^"]*)" invocation="([^"]*)">/;function
|
|
5
|
-
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}function
|
|
6
|
-
---`);r!==-1&&(t=n.slice(r+4))}return Ot(t)!==""}function
|
|
3
|
+
`,n),i=s===-1?e.length:s;let a=e.slice(r,i);return a.endsWith("\r")&&(a=a.slice(0,-1)),{line:a,lineStart:r,column:n-r}}function gm(e,t){if(t.size===0)return null;for(const n of $l(e)){const r=e.slice(n+1),s=r.indexOf(" ");if(s!==-1&&t.has(r.slice(0,s).toLowerCase()))return n}return null}function co(e,t,n){const r=gm(e,n);let s=null;for(const i of $l(e)){if(i===r)return t>i?i:s;i<=t&&(s=i)}return s}function ym(e,t=null,n=oo){const{line:r,lineStart:s,column:i}=ao(e,t),a=co(r,i,n);if(a===null)return null;let c=a+1;for(;c<r.length&&!Ll.test(r[c]);)c++;return i>c?null:{start:s+a,query:r.slice(a+1,c),end:s+c}}function Ek(e,t=null,n=oo){const{line:r,lineStart:s,column:i}=ao(e,t),a=co(r,i,n);return a===null?null:{start:s+a,end:s+r.length}}function _m(e,t,n=null,r=oo){const{line:s,lineStart:i,column:a}=ao(e,n),c=r.size>0?r:new Set(t.map(h=>h.toLowerCase())),l=co(s,a,c);if(l===null)return null;const d=s.slice(l+1),u=d.indexOf(" ");if(u===-1)return null;const f=d.slice(0,u);if(!t.some(h=>h.toLowerCase()===f.toLowerCase()))return null;const p=l+1+f.length;return a<=p?null:{value:d.slice(u+1),start:i+p+1,end:i+s.length,tokenStart:i+l}}function Ya(e,t){return Ot(e.slice(0,t))===""}function Ik(e,t,n,r){const s=_m(e,r,t,n);if(s!==null&&Ya(e,s.tokenStart))return"argument";const i=ym(e,t,n);return i!==null&&Ya(e,i.start)?"command":null}function xk(e,t,n,r){let s=t,i=n;const a=c=>c>=0&&c<e.length&&`
|
|
4
|
+
`.includes(e[c]);return r===""?s>0&&a(s-1)?s-=1:a(i)&&(i+=1):s===0&&a(i)&&(i+=1),{text:`${e.slice(0,s)}${r}${e.slice(i)}`,caret:s+r.length}}const vm=/^\$([A-Za-z0-9][A-Za-z0-9._-]*)/,bm=/<skill name="([^"]*)" invocation="([^"]*)">/;function Tk(e,t){const n=lr(e),r=vm.exec(n);if(!r)return null;const s=r[1];let i=t.includes(s)?s:void 0;if(i===void 0){const c=s.toLowerCase();i=t.find(l=>l.toLowerCase()===c)}if(i===void 0)return null;const a=Ot(n.slice(r[0].length));return{name:i,request:a,token:r[0],typed:Ot(n)}}function wm(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ")}function Sm(e){return e.replace(/ /g,`
|
|
5
|
+
`).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")}function Ck(e){if(!e||Ot(e)==="")return!1;let t=lr(e);if(t.startsWith("---")){const n=t.slice(3),r=n.indexOf(`
|
|
6
|
+
---`);r!==-1&&(t=n.slice(r+4))}return Ot(t)!==""}function Ak(e,t){const n=`The user invoked the \`${e.name}\` skill directly. Follow it for this request. Its reference files, if any, are listed at the end of the body and are read with \`skill://<name>/<path>\`.`,r=wm(e.typed),s=[n,`<skill name="${e.name}" invocation="${r}">`,t,"</skill>"];return e.request&&s.push(e.request),s.join(`
|
|
7
7
|
`)}const Ae=[];for(let e=0;e<256;++e)Ae.push((e+256).toString(16).slice(1));function km(e,t=0){return(Ae[e[t+0]]+Ae[e[t+1]]+Ae[e[t+2]]+Ae[e[t+3]]+"-"+Ae[e[t+4]]+Ae[e[t+5]]+"-"+Ae[e[t+6]]+Ae[e[t+7]]+"-"+Ae[e[t+8]]+Ae[e[t+9]]+"-"+Ae[e[t+10]]+Ae[e[t+11]]+Ae[e[t+12]]+Ae[e[t+13]]+Ae[e[t+14]]+Ae[e[t+15]]).toLowerCase()}let zs;const Rm=new Uint8Array(16);function Em(){if(!zs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");zs=crypto.getRandomValues.bind(crypto)}return zs(Rm)}const Im=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Qa={randomUUID:Im};function xm(e,t,n){if(Qa.randomUUID&&!e)return Qa.randomUUID();e=e||{};const r=e.random??e.rng?.()??Em();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,km(r)}const Ul=/^\s*<reply-to>([\s\S]*?)<\/reply-to>/,Fl=e=>{let t=e;for(;;){const n=Ul.exec(t);if(n===null)break;t=t.slice(n[0].length)}return{prefix:e.slice(0,e.length-t.length),rest:t}},Tm=e=>{const t=[];let n=e;for(;;){const r=Ul.exec(n);if(r===null)break;t.push({id:xm(),text:r[1]}),n=n.slice(r[0].length)}return{replies:t,remainingContent:n.trim()}};function ms(e){return Bl(e)?.skill}const Cm=/^\s/,Am=/^[>|](?:[-+]\d?|\d[-+]?)?(?:\s+#.*)?$/,Om=/^The user invoked the `([^`\n]+)` skill directly\.[^\n]*\n/;function Pm(e){const t=lr(e);if(!t.startsWith("---"))return null;const r=t.slice(3).indexOf(`
|
|
8
8
|
---`);return r===-1?null:e.length-t.length+3+r+4}function jm(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Ja(e,t){const n=[];for(let r=1;r<e.length;r+=1){const s=e[r];if(t==='"'&&s==="\\"&&r+1<e.length){n.push(s,e[r+1]),r+=1;continue}if(s!==t){n.push(s);continue}if(t==="'"&&e[r+1]==="'"){n.push(s,s),r+=1;continue}const i=e.slice(r+1).trim();if(i!==""&&!i.startsWith("#"))return null;const a=n.join(""),c=t==="'"?a.replace(/''/g,"'"):jm(a);return c===""?null:c}return null}function Mm(e){const t=e.split(`
|
|
9
|
-
`);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),i=s!==""&&Am.test(s),a=[];s!==""&&!i&&a.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!Cm.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return Ja(c,'"');if(c.startsWith("'"))return Ja(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Bl(e){const{prefix:t,rest:n}=Fl(e),r=n.slice(0,n.length-lr(n).length),s=lr(n),i=Om.exec(s);if(i===null)return null;const a=bm.exec(s.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=Pm(d),f=u===null?null:Mm(d.slice(0,u)),p=a[1],h=Sm(a[2]);return{text:t+r+h,skill:{name:p,token:`$${p}`,request:Ot(s.slice(l+8)),purpose:f,body:Ot(u===null?d:d.slice(u))}}}function Dm(e){const t=Bl(e);if(t===null)return null;const{prefix:n}=Fl(e);return{replies:Tm(e).replies,text:t.text.slice(n.length).trimStart()}}function
|
|
9
|
+
`);for(const[n,r]of t.entries()){if(!r.startsWith("description:"))continue;const s=r.slice(12).trim(),i=s!==""&&Am.test(s),a=[];s!==""&&!i&&a.push(s);for(let u=n+1;u<t.length;u+=1){const f=t[u];if(f.trim()!==""){if(!Cm.test(f))break;a.push(f.trim())}}if(a.length===0)return null;const c=a.join(" ");if(i)return c.trim()===""?null:c.trim();if(c.startsWith('"'))return Ja(c,'"');if(c.startsWith("'"))return Ja(c,"'");const l=c.indexOf(" #"),d=(l===-1?c:c.slice(0,l)).trim();return d===""?null:d}return null}function Bl(e){const{prefix:t,rest:n}=Fl(e),r=n.slice(0,n.length-lr(n).length),s=lr(n),i=Om.exec(s);if(i===null)return null;const a=bm.exec(s.slice(i[0].length));if(a===null||a.index!==0||a[1]!==i[1])return null;const c=i[0].length+a[0].length,l=s.indexOf("</skill>",c);if(l===-1)return null;const d=s.slice(c,l),u=Pm(d),f=u===null?null:Mm(d.slice(0,u)),p=a[1],h=Sm(a[2]);return{text:t+r+h,skill:{name:p,token:`$${p}`,request:Ot(s.slice(l+8)),purpose:f,body:Ot(u===null?d:d.slice(u))}}}function Dm(e){const t=Bl(e);if(t===null)return null;const{prefix:n}=Fl(e);return{replies:Tm(e).replies,text:t.text.slice(n.length).trimStart()}}function Ok(e){return Dm(e)?.text??e}const Nm=new Map([["This changes your instructions. Apply it from now on, and drop work it makes pointless.","steer"],["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.","ask"],["This is a note, not a question. No reply is needed unless it changes what you should do.","note"]]),Lm=/\blabel=(['"])(.*?)\1/,$m=/\bjob=(['"])(.*?)\1/,Um=/^<(parent-message|subagent-message)\b[^>]*>\n([\s\S]*)\n<\/\1>$/;function Si(e){const t=typeof e.text=="string"?e.text:"",n=Um.exec(t);let r=n?.[2];const s=r?.indexOf(`
|
|
10
10
|
|
|
11
11
|
`)??-1,a=n?.[1]==="parent-message"&&(e.direction===void 0||e.direction===""||e.direction==="to_child")&&s>=0?Nm.get((r??"").slice(0,s)):void 0;n?.[1]==="parent-message"&&a&&(r=(r??"").slice(s+2));const c=typeof e.direction=="string"?e.direction:n?.[1]==="subagent-message"?"to_parent":a?"to_child":"";return{body:typeof e.body=="string"?e.body:r?.trim()?r:t,envelope:t,direction:c,label:dr(e.label??(n&&Lm.exec(n[0].split(`
|
|
12
12
|
`,1)[0])?.[2])),jobId:dr(e.job_id??(n&&$m.exec(n[0].split(`
|
|
13
|
-
`,1)[0])?.[2])),sender:Vl(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function
|
|
13
|
+
`,1)[0])?.[2])),sender:Vl(e).sender,expectsReply:typeof e.expects_reply=="boolean"?e.expects_reply:e.expects_reply===void 0&&a?a==="ask":null,steer:typeof e.steer=="boolean"?e.steer:e.steer===void 0&&a?a==="steer":null}}function Pk(e){return[e.label||e.jobId||e.sender.conversationName||e.sender.sessionId||(e.direction==="to_child"?"Parent":e.direction==="to_parent"?"Subagent":"Hub"),e.expectsReply?"Reply requested":"",e.steer?"Steered":""].filter(Boolean).join(" · ")}function Fm(e){if(e.kind==="peer")return"incoming";if(e.kind==="wake")return"wake";if(e.kind!=="custom")return null;switch(e.customType){case"hub_message":return"incoming";case"job_result":return"job_result";case"monitor_prompt":return"monitor_prompt";default:return null}}function jk(e){return Fm(e)!==null}const Gl=/\s+/,Bm=/[\\/]+$/,Gm=/[\\/]/,Hl=`
|
|
14
14
|
|
|
15
|
-
`,Hm=" — cancel with wake(",Wm=120,Wl=/(?:\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,zm=new RegExp("\\p{Cf}","gu"),Zm=4096;function dr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Wl,"").replace(zm,"").split(Gl).filter(Boolean).join(" ").slice(0,Wm)}const
|
|
16
|
-
`)){const n=dr(t);if(n)return n}return""}function
|
|
17
|
-
`)){const r=n.trim();if(r&&!wg.test(r))return`${Sg}${r.slice(0,160)}`}return null}function Jl(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),i=t%60;return i===0?`${s}m`:`${s}m${i}s`}if(t<86400){const s=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${s}h`:`${s}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function
|
|
18
|
-
`):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function Cg(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 td(e,t){return e===null||Cg(e,t)?t:e}function nd(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:tc(n.added),removed:tc(n.removed)}}function Ag(e){return e.length>=2&&Ri(e[0])==="---"&&Ri(e[1])==="+++"?e.slice(2):e.slice()}const Og=/\s+$/;function Ri(e){return e.replace(Og,"")}function Pg(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const jg=40;function
|
|
15
|
+
`,Hm=" — cancel with wake(",Wm=120,Wl=/(?:\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,zm=new RegExp("\\p{Cf}","gu"),Zm=4096;function dr(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(Wl,"").replace(zm,"").split(Gl).filter(Boolean).join(" ").slice(0,Wm)}const Mk={pid:"",conversationName:"",cwd:"",sessionId:"",modelLabel:""};function zl(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(Bm,"");if(t){const n=t.split(Gm).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function Zl(e){const{name:t,quoted:n}=zl(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function Vm(e){const{name:t,quoted:n}=zl(e),r=[];return e.pid&&r.push(`pid ${e.pid}`),e.modelLabel&&r.push(e.modelLabel),t?[n?`"${t}"`:t,...r].join(" · "):r.length>0?r.join(" · "):"another session"}function Dk(e,t){return t.trim()?!0:Vm(e)!==Zl(e)}function Km(e){for(const t of e.slice(0,Zm).split(`
|
|
16
|
+
`)){const n=dr(t);if(n)return n}return""}function Nk(e,t){const n=Zl(e),r=Km(t);return r?`${n} · ${r}`:n}function Zs(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const Ym=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Qm=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Jm=/^<peer-session-message[^>]*>/,Xm=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Vl(e){const t=String(e.text??e.detail??""),n=Ym.exec(t.trim()),r={};if(n)for(const d of n[1].matchAll(Xm))r[d[1]]=d[2]??d[3]??d[4]??"";const s=n?n[2]:"",a=(String(e.body??"").trim()||s||(n?"":t.trim().replace(Jm,""))).replace(Qm,"").trim(),c=e.sender??{},l=(d,u)=>dr(d)||dr(u);return{body:a,sender:{pid:l(c.pid,r.from_pid),conversationName:l(c.conversation_name,r.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,r.model)}}}function qm(e){return!!e.wake_catchup}function eg(e){return e.hidden===!0}function Lk(e){let t=e.split(Hl)[0]??"";t=t.split(Gl).filter(Boolean).join(" "),t=t.split(Hm)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const r="Scheduled wake ";return t.startsWith(r)&&(t=t.slice(r.length)),t.trim()}function $k(e){const t=e.indexOf(Hl);return t===-1?"":e.slice(t+2).trim()}const tg=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),ng=new Set(["true","yes","y","t","on","1"]),rg={hub:{steps:e=>{const t=yn(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=yn(e);return t!==null&&t>0?`· ${Jl(t/1e3)}`:""}}};function yn(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 Xa="mcp__",sg=/^\/(?:Users|home)\/[^/]+\//,ig=/\s+/;function og(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(sg,"~/")}function Ze(e){return typeof e=="string"?og(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function ag(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function cg(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(ig).filter(Boolean).join(" ")||"?"}function lg(e){return[ag(e),Ze(cg(e))||"?",Ze(e.message)].filter(Boolean).join(" · ")}const dg=new Set(["delivered","mailbox","unconfirmed","failed"]);function ug(e){if(!e||typeof e!="object")return null;const t=e.delivery;if(!t||typeof t!="object")return null;const n=t.state;return typeof n=="string"&&dg.has(n)?n:null}function Kl(e,t){return!e||typeof e!="object"?t??null:ug(e)}function fg(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return!("stage"in t)&&!("error_type"in t)&&!("billing_basis"in t)&&!("settled"in t)&&!("artifacts"in t)&&!(typeof t.total=="number"&&typeof t.item=="number")?null:t}const pg=["stage","queue_position","progress_fraction","log_lines","error","error_type","cost_usd","billing_basis","settled","cost","artifacts","cost_complete","completed","failed","cancelled","total","item","name"];function hg(e,t){if(e===t)return!0;if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!(!!r&&typeof r=="object")||!(!!s&&typeof s=="object")){if(r!==s)return!1;continue}const c=r,l=s;if(c.message!==l.message||c.timestamp!==l.timestamp)return!1}return!0}const mg=["name","digest","path","duration_s","format","cost_usd","billing_basis","request_id","error","status","cost"];function gg(e,t){return e===t?!0:!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return!n||typeof n!="object"||!s||typeof s!="object"?n===s:mg.every(i=>i==="cost"?n.cost?.basis===s.cost?.basis:n[i]===s[i])})}function yg(e,t){for(const n of pg){const r=e[n],s=t[n];if(n==="artifacts"){if(!gg(r,s))return!1;continue}if(n==="cost"){const i=a=>a&&typeof a=="object"?a.basis:void 0;if(i(r)!==i(s))return!1;continue}if(n==="log_lines"){if(!hg(r,s))return!1;continue}if(r!==s)return!1}return!0}function ki(e,t){const n=fg(e);return n?t&&yg(n,t)?t:n:t??null}const Uk={mailbox:"wake unconfirmed",unconfirmed:"delivery unconfirmed",failed:"not delivered"},Fk={mailbox:"In their mailbox. The wake got no answer, so they will read it on their next turn.",unconfirmed:"No wake answer and not yet in their transcript — it may still arrive. Check before resending."},Bk={mailbox:"Delivered to their mailbox. The wake got no answer, so they will read the message on their next turn. Do not send it again.",unconfirmed:"Not confirmed: there was no answer and the message is not in their transcript. It may still arrive, so check before resending.",failed:"Nothing was delivered. Fix the cause named below, or retry the send."},Gk={mailbox:"delivered, wake unconfirmed",unconfirmed:"delivery unconfirmed — it may still arrive, so check before resending"};function Yl(e){return e==="mailbox"||e==="unconfirmed"}function Hk(e){return Yl(e)?"partial":null}function Wk(e){return e==="failed"?"Attempted":null}function zk(e,t){return e!==!0?!1:!Yl(t)}function qa(e){const t=yn(e.pid);return t!==null&&Number.isInteger(t)?`pid ${t}`:Ze(e.session)||Ze(e.target)||"?"}function _g(e){const t=Ze(e.query);if(t){const a=yn(e.steps);return a!==null&&Number.isInteger(a)&&a>=0?`search ${t} · ${a} around`:`search ${t}`}const n=yn(e.steps);if(n!==null&&Number.isInteger(n)&&n>=0)return`last ${n}`;const r=yn(e.head);if(r!==null&&Number.isInteger(r)&&r>=0)return`first ${r}`;if(e.digest===!0)return"digest";const s=Ze(e.before_id);if(s)return`before ${s}`;const i=Ze(e.around_id);return i?`around ${i}`:""}function vg(e){const t=kg(e);if(t==="spawn"){const n=Ze(e.visibility)||"workstream",r=Ze(e.name)||Ze(e.prompt);return[n,r].filter(Boolean).join(" · ")}if(t==="stop"||t==="resume"||t==="info")return qa(e);if(t==="peek")return[qa(e),_g(e)].filter(Boolean).join(" · ");if(t==="list"){const n=[];e.include_stored===!0&&n.push("stored");const r=Ze(e.query);return r&&n.push(r),n.join(" · ")}return null}function Zk(e,t){const n=e.trim();if(!t)return n;if(n==="send")return lg(t)||n;if(n.toLowerCase()==="sessions"){const i=vg(t);if(i!==null)return i||n}const r=Rg(n)?Object.entries(t).filter(([i])=>!Xl.has(i)):Object.entries(t);let s=r.filter(([i])=>tg.has(i)).map(([,i])=>Ze(i)).filter(Boolean);if(s.length===0){const i=rg[n.toLowerCase()];s=r.map(([a,c])=>i?.[a]?.(c)||Ze(c)).filter(Boolean)}return s.slice(0,2).join(" ")||n}function Ql(e){const t=e.trim();if(!t.toLowerCase().startsWith(Xa))return t;const n=t.slice(Xa.length),r=n.indexOf("_");return r<=0?n||t:n.slice(r+1)||n}function bg(e,t){return e===t||e===Ql(t)}const wg=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Sg="… ";function Vk(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
17
|
+
`)){const r=n.trim();if(r&&!wg.test(r))return`${Sg}${r.slice(0,160)}`}return null}function Jl(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const s=Math.floor(t/60),i=t%60;return i===0?`${s}m`:`${s}m${i}s`}if(t<86400){const s=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${s}h`:`${s}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const r=Math.floor(t%86400/3600);return r===0?`${n}d`:`${n}d${r}h`}function Kk(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`:Jl(t)}function ec(e){const t=e*10,n=Math.floor(t),r=t-n;return((r>.5?n+1:r<.5||n%2===0?n:n+1)/10).toFixed(1)}function Yk(e){return e<1024?`${e} B`:e<1024*1024?`${ec(e/1024)} KB`:`${ec(e/(1024*1024))} MB`}function tc(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const nc={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",sessions:"meta"};function Qk(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(nc,t)?nc[t]:"plain"}function kg(e){if(!e)return"";for(const t of Xl){const n=e[t];if(typeof n=="string"&&n.trim()){const r=n.trim().toLowerCase(),s=e.remove,i=s===!0||s===1||typeof s=="string"&&ng.has(s.toLowerCase());return r==="milestone"&&i?"milestone-remove":r}}return""}const Xl=new Set(["op","action","method"]),Rg=e=>Object.prototype.hasOwnProperty.call(ql,e.trim().toLowerCase()),Eg={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"}},ql={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"}},sessions:{list:{settled:"Listed sessions",running:"Listing sessions"},info:{settled:"Viewed session",running:"Viewing session"},spawn:{settled:"Spawned session",running:"Spawning session"},resume:{settled:"Resumed session",running:"Resuming session"},stop:{settled:"Stopped session",running:"Stopping session"},peek:{settled:"Peeked at session",running:"Peeking at session"}}};function Ig(e,t){const n=e.trim().toLowerCase(),r=(t??"").trim().toLowerCase(),s=r?ql[n]?.[r]:void 0;if(s)return{...s,named:!0};const i=Eg[n];return i?{...i,named:!0}:{settled:"Called",running:"Calling",named:!1}}function Jk(e,t,n,r,s="",i=null){const a=Ig(e,s),c=bg(t,e)?n??"":t;return{verb:r?a.running:i??a.settled,object:a.named?c:[Ql(e),c].filter(Boolean).join(" ")}}const xg=new Set(["write","edit"]);function Tg(e){return xg.has(e.trim().toLowerCase())}function Xk(e){return Tg(e.toolName)&&e.diff!==null&&!e.isError}function ed(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
|
|
18
|
+
`):null;if(!Array.isArray(t))return null;const n=t.filter(r=>typeof r=="string");return n.length?n:null}function Cg(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 td(e,t){return e===null||Cg(e,t)?t:e}function nd(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:tc(n.added),removed:tc(n.removed)}}function Ag(e){return e.length>=2&&Ri(e[0])==="---"&&Ri(e[1])==="+++"?e.slice(2):e.slice()}const Og=/\s+$/;function Ri(e){return e.replace(Og,"")}function Pg(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const jg=40;function qk(e){const t=Ag(e),n=t.slice(0,jg);return{lines:n.map(r=>{const s=Ri(r);return{text:s,marker:s.slice(0,1),kind:Pg(s)}}),hidden:t.length-n.length}}function eR(e){return`… ${e} more diff line${e===1?"":"s"}`}const Mg=`Continue working toward this goal:
|
|
19
19
|
|
|
20
20
|
`,Dg=`
|
|
21
21
|
|
|
@@ -23,7 +23,7 @@ Make concrete progress with the tools available, then state plainly what advance
|
|
|
23
23
|
|
|
24
24
|
{goal}
|
|
25
25
|
|
|
26
|
-
Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[Lg="",$g=""]=Ng.split("{goal}"),Ug="Continue working toward the standing goal. Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly and stop.";function rd(e){const t=e.trim();return t===Ug||t.startsWith(Mg)&&t.endsWith(Dg)||t.startsWith(Lg.trim())&&t.endsWith($g.trim())}const Fg=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Bg(e,t){const n=t?.match(Fg)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,i=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(s.toFixed(4));return`Cost ${a===0&&s>0?"<$0.0001":`$${a}`} (${i}).`}function sd(e){return e}const Ei="supplement_v1",Gg="superseded",ns=120,lo=480,Hg=20,eR=500;function uo(e){return`supplement:${e}`}function Wg(e){const t=e.payload??{};if(String(t.custom_type??"")!==Ei)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?uo(r):null}function rs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:rs(t.size_bytes)??0,mtime:rs(t.mtime)??0,why:typeof t.why=="string"?t.why:""}}function id(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=zg(n);r&&t.push(r)}return t}function Zg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!cd(n))return null;const r=rs(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?ns:Math.min(lo,Math.max(ns,Math.round(r)))}}function od(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Zg(n);r&&t.push(r)}return t}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return cd(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:rs(t.duration_s)}:null}function ad(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Vg(n);r&&t.push(r)}return t}const Kg=/^[a-f0-9]{32}$/,Yg=/\s+/,Qg=/\.0$/;function cd(e){return typeof e=="string"&&Kg.test(e)}const Jg={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function rc(e){switch(e){case"decided":return 0;case"queued":return 1;case"running":return 2;case"cancelling":return 3;case"done":case"failed":case"cancelled":case"skipped":return 4;default:return 0}}function tR(e,t){const n=e.state;if(e.error===Gg||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?Jg[r]??r:r}const nR="Preparing highlights…",rR="Highlights cancelled",sR="Couldn't prepare highlights",iR="Adjust…",oR="Cancel",aR="Retry",Xg=64,qg={provider_quota:"provider limit reached",provider_auth:"provider sign-in needed",provider_transient:"provider temporarily unavailable",provider_timeout:"provider timed out",provider_request:"provider refused the request",provider_content:"provider blocked the content",provider_context:"provider context limit"};function cR(e){return typeof e=="string"&&e?qg[e]??"":""}function Vs(e){return typeof e!="string"?"":e.replace(Wl,"").split(Yg).filter(Boolean).join(" ")}function lR(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function ey(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.trunc(e)} B`;const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB")return`${(e/r).toFixed(1).replace(Qg,"")} ${n}`;return""}function dR(e){const t=Vs(e.name)||Vs(e.path),n=Vs(e.path);return{name:t,path:n===t?"":n,size:ey(e.sizeBytes)}}function Ks(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function uR(e,t,n=e){return t?`Hide ${Ks(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Ks(e,"graphic")}`:`Show ${Ks(e,"graphic")}`}function fR(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const ty="supplement",ny=1,ry=["ready","resize","error","pong"],sy=["resize","error","pong"],iy=64,fo=300,pR=5e3,hR=2e4;function mR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==ty||n.v!==ny)return null;const r=n.t;if(typeof r!="string"||!ry.includes(r))return null;const s=r;if(sy.includes(s)&&(!t||t.length>iy||n.n!==t))return null;if(s==="error"){const i=n.msg;if(typeof i!="string"||i.length>fo)return null}if(s==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<0)return null}return{lo:"supplement",v:1,t:s,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function gR(){const e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}const oy=["--lo-accent","--lo-accent-wash","--lo-border-control","--lo-canvas","--lo-danger","--lo-hairline","--lo-info","--lo-ink","--lo-ink-dim","--lo-ink-muted","--lo-success","--lo-sunken","--lo-surface","--lo-warning","--font-mono","--font-sans"],ay=120;function cy(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const s of oy){const i=t.getPropertyValue(s).trim();i&&(n[s]=i.slice(0,ay))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function yR(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(cy()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function _R(e){return`data:text/html;base64,${ly(e)}`}function ly(e){const t=dy(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const i=t[s]??0,a=t[s+1]??0,c=t[s+2]??0;r+=n[i>>2],r+=n[(i&3)<<4|a>>4],r+=s+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function dy(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function vR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function uy(e){return Math.min(lo,Math.max(ns,e.heightHint))}function fy(e){return Math.min(lo,Math.max(ns,e))}function bR(e,t,n){let r=0;const s=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?fy(c):uy(a);if(i>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(a)}return{visible:s,hidden:e.slice(s.length)}}const py=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,ld=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,hy=/kind=(auth|quota)\b/,my=/kind=(transient|timeout)\b/;function dd(e){const t=a=>typeof a=="string"&&py.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,s=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(ld.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,Xg):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...i?{cause:i}:{}}}function wR(e){if(!ld.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),i=n[4].slice(5);return`Attempt ${r}: ${i}${s==="None"?"":` (HTTP ${s})`}`}function SR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return hy.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":my.test(t)?"The highlights service did not respond. Your answer and files are unchanged.":e.error==="bound:cost"?"Highlights stopped at the spending limit or unavailable pricing. Your answer and files are unchanged.":e.error==="bound:time"?"Highlights reached the time limit. Your answer and files are unchanged.":"Your answer and files are unchanged. You can retry the highlights."}function gy(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return ud(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:id(e.files)}:{},...n==="done"?{components:od(e.components),sounds:ad(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,fo)}:{},...dd(e),live:!fd(n)}:null}function yy(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!ud(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,s=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,Hg):[];return{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,files:id(e.files),filesMore:r,more:s,components:od(e.components),sounds:ad(e.sounds),...dd(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,fo)}:{}}}function sc(e,t,n){const r=yy(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return pd(s,r,e)}function ud(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function fd(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function _y(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.path===s.path&&n.name===s.name&&n.kind===s.kind&&n.sizeBytes===s.sizeBytes&&n.mtime===s.mtime&&n.why===s.why})}function vy(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.title===s.title&&n.source===s.source&&n.mime===s.mime&&n.heightHint===s.heightHint})}function by(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.mime===s.mime&&n.title===s.title&&n.durationS===s.durationS})}function pd(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&rc(t.state)<rc(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],i=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,l=t.more!==void 0?t.more:e?.more??[],d=t.error??(r?"":e?.error??""),u=t.cause??(r?"":e?.cause??""),f=t.dismissed??(r?!1:e?.dismissed??!1),p=t.live!==void 0?t.live===!0?!0:fd(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:uo(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:_y(s,e?.files??[])?e?.files??[]:s,filesMore:c,more:wy(l,e?.more??[])?e?.more??[]:l,components:vy(i,e?.components??[])?e?.components??[]:i,sounds:by(a,e?.sounds??[])?e?.sounds??[]:a,error:d,cause:u,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:f,live:p}}function wy(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const kR=e=>e.kind===void 0||e.kind==="image",st={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function hd(e){return e==="skipped"||e==="aborted"}function ic(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function oc(e,t,n,r){return ic(n.args)??(r?.kind==="tool"?r.args:null)??ic(e.argsByCall.get(t)?.arguments)}function md(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function gd(e){if(!e)return null;const t=e.kind;return t!=="image"&&t!=="video"&&t!=="audio"?null:typeof e.content_type=="string"||typeof e.attachment=="string"||typeof e.source_url=="string"?t:null}function Lr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!md(n)&&gd(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Zt(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Vn;const s=[];for(const i of r){const a=gd(i);if(i.type==="document"||a===null&&!md(i))continue;const c={id:`${t}:${s.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Lr(i.width),c.height=Lr(i.height),c.sizeBytes=Lr(i.size_bytes),c.durationS=Lr(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),s.push(c)}return s.length===0?Vn:n&&po(n,s)?n:s}const Vn=[],Ii=[];function Sy(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Ii;const s=[];for(const i of r){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||s.push({id:`${t}:doc:${s.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return s.length===0?n?.length?n:Ii:n&&ky(n,s)?n:s}function ky(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.id===s.id&&n.attachment===s.attachment&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.path===s.path&&n.storedPath===s.storedPath&&n.bytes===s.bytes&&n.injection===s.injection})}function ac(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function yd(e,t,n){if(t.length===0)return e;if(e.length===0||po(e,t))return t;const r=ac(e),s=ac(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function Ry(e,t){return yd(e,t,"incoming")}function po(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||e[n].kind!==t[n].kind||e[n].width!==t[n].width||e[n].height!==t[n].height||e[n].sizeBytes!==t[n].sizeBytes||e[n].durationS!==t[n].durationS||e[n].name!==t[n].name||e[n].sourceUrl!==t[n].sourceUrl)return!1;return!0}function Ke(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Ey(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const kt=new Set;function ho(e){return e.kind==="user"&&e.provisional===!0}function _d(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{ho(n)&&r<t&&(t=r)}),t}function ur(e,t=kt,n){if(n?.journalMode)return Dl(n,e).map(sd);const r=e.map((a,c)=>({record:a,position:c})),s=_d(e),i=a=>ho(a.record)||a.position>s&&!t.has(a.record.id);return r.sort((a,c)=>{const l=i(a),d=i(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function Iy(e,t,n){if(!n||t<=0)return kt;let r=null;for(const s of e){if(!ho(s)||!(t>s.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>s.ts?i=!0:c.ts<s.ts&&_o(c)&&(a=!0),i&&a)break;i&&a&&(r??=new Set,r.add(s.id))}return r??kt}function xy(e){const{provisional:t,...n}=e;return n}function xi(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const i of s)if(n[i]!==r[i]){if(i==="images"){const a=n[i],c=r[i];if(Array.isArray(a)&&Array.isArray(c)&&po(a,c))continue}if(i==="frame"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&Ty(a,c))continue}return!1}return!0}function Ty(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function ge(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(xi(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=ur(a,kt,e);return{...e,records:c,index:Ke(c)}}const r=e.journalMode?ur([...e.records,t],kt,e):[...e.records,t],s=Ke(r);return{...e,records:r,index:s}}function mo(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Ke(n)}}function Ys(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const s=e.records[r];return s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")?mo(e,i=>i.id===n):e}function Cy(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const s=e.records[r];if(!(s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")))return e;const i=e.records.slice();return i[r]=n,{...e,records:i,index:Ke(i)}}const Ay=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function vd(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 Oy(e,t){const n=yc(e),r=yc(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const bd="Context compacted",Py=12e4;function wd(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 r=new Set,s=new Set,i=new Map,a=(d,u)=>{r.add(u.id),s.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=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!s.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Py||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)s.has(d.id)||r.has(u.id)||a(d,u);return s.size===0?e:e.filter(d=>!s.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 jy(e){const t=wd(e.records);return t===e.records?e:{...e,records:t,index:Ke(t)}}const My="peer_message",Dy="ask_response",Ny="ask_timeout",Sd="Completed — runtime retired/disposed",kd="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Ly="wake_prompt",$y="session_mcp_unavailable",Uy=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),Fy=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,cc=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,By=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."]),Rd=/^\[[^\]]{1,32}\]\s*/,ss="Reason:",Gy=/[\n;,(]| [—–] /,Hy=/^\d+\.$/,Wy=/[A-Z]/,zy=/\s/,Kn=160;function Wr(e,t,n){if(e==="audio_settle_v1")return{level:"info",headline:t,detail:null,category:"Audio settlement",provider:null};if(e==="session_incident")return{level:"error",...Qy(t,n)};let r;return e===$y?r=Zy(t):Uy.has(e)?r=Ky(t.trim().replace(Rd,"")):r=Jy(t),{level:"info",category:null,provider:null,...r}}function Zy(e){const t=e.trim().replace(Rd,"").split(`
|
|
26
|
+
Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly.`,[Lg="",$g=""]=Ng.split("{goal}"),Ug="Continue working toward the standing goal. Make concrete progress with the tools available, then briefly state what advanced and what remains. If the goal is already fully met, say so plainly and stop.";function rd(e){const t=e.trim();return t===Ug||t.startsWith(Mg)&&t.endsWith(Dg)||t.startsWith(Lg.trim())&&t.endsWith($g.trim())}const Fg=/Cost \$[0-9]+(?:\.[0-9]+)? \((?:billed|estimated[^)]*)\)\.?/;function Bg(e,t){const n=t?.match(Fg)?.[0]??null;if(!e||typeof e!="object")return n;const r=e,s=r.cost_usd,i=r.billing_basis;if(typeof s!="number"||!Number.isFinite(s)||s<0)return n;if(i!=="billed"&&i!=="estimated")return null;const a=Number(s.toFixed(4));return`Cost ${a===0&&s>0?"<$0.0001":`$${a}`} (${i}).`}function sd(e){return e}const Ei="supplement_v1",Gg="superseded",ns=120,lo=480,Hg=20,tR=500;function uo(e){return`supplement:${e}`}function Wg(e){const t=e.payload??{};if(String(t.custom_type??"")!==Ei)return null;const n=t.details??{},r=typeof n.anchor=="string"?n.anchor:"";return r?uo(r):null}function rs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function zg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.path=="string"?t.path:"",r=typeof t.name=="string"?t.name:"";return!n&&!r?null:{path:n,name:r,kind:typeof t.kind=="string"?t.kind:"",sizeBytes:rs(t.size_bytes)??0,mtime:rs(t.mtime)??0,why:typeof t.why=="string"?t.why:""}}function id(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=zg(n);r&&t.push(r)}return t}function Zg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";if(!cd(n))return null;const r=rs(t.height_hint);return{attachment:n,title:typeof t.title=="string"?t.title:"",source:typeof t.source=="string"?t.source:"",mime:typeof t.mime=="string"?t.mime:"text/html",heightHint:r===null?ns:Math.min(lo,Math.max(ns,Math.round(r)))}}function od(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Zg(n);r&&t.push(r)}return t}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.attachment=="string"?t.attachment:"";return cd(n)?{attachment:n,mime:typeof t.mime=="string"?t.mime:"audio/mpeg",title:typeof t.title=="string"?t.title:"",durationS:rs(t.duration_s)}:null}function ad(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=Vg(n);r&&t.push(r)}return t}const Kg=/^[a-f0-9]{32}$/,Yg=/\s+/,Qg=/\.0$/;function cd(e){return typeof e=="string"&&Kg.test(e)}const Jg={preparing:"files_preparing",cancelled_retry:"files_cancelled_retry",failed_retry:"files_failed_retry"};function rc(e){switch(e){case"decided":return 0;case"queued":return 1;case"running":return 2;case"cancelling":return 3;case"done":case"failed":case"cancelled":case"skipped":return 4;default:return 0}}function nR(e,t){const n=e.state;if(e.error===Gg||e.dismissed||n==="skipped")return"nothing";if(n==="done")return e.files.length||e.components.length||e.sounds?.length?"block":"nothing";let r;if(n==="failed")r="failed_retry";else if(n==="cancelled")r="cancelled_retry";else if(n==="decided"||n==="queued"||n==="running"||n==="cancelling")r=t?"preparing":"cancelled_retry";else return"nothing";return e.files.length?Jg[r]??r:r}const rR="Preparing highlights…",sR="Highlights cancelled",iR="Couldn't prepare highlights",oR="Adjust…",aR="Cancel",cR="Retry",Xg=64,qg={provider_quota:"provider limit reached",provider_auth:"provider sign-in needed",provider_transient:"provider temporarily unavailable",provider_timeout:"provider timed out",provider_request:"provider refused the request",provider_content:"provider blocked the content",provider_context:"provider context limit"};function lR(e){return typeof e=="string"&&e?qg[e]??"":""}function Vs(e){return typeof e!="string"?"":e.replace(Wl,"").split(Yg).filter(Boolean).join(" ")}function dR(e){const t=Math.max(0,Math.floor(e));return t===1?"1 more file":`${t} more files`}function ey(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${Math.trunc(e)} B`;const t=[["KB",1024],["MB",1024**2],["GB",1024**3]];for(const[n,r]of t)if(e<r*1024||n==="GB")return`${(e/r).toFixed(1).replace(Qg,"")} ${n}`;return""}function uR(e){const t=Vs(e.name)||Vs(e.path),n=Vs(e.path);return{name:t,path:n===t?"":n,size:ey(e.sizeBytes)}}function Ks(e,t){const n=Math.max(0,Math.floor(e));return n===1?`1 ${t}`:`${n} ${t}s`}function fR(e,t,n=e){return t?`Hide ${Ks(e,"graphic")}`:n<e?`Show ${Math.max(0,Math.floor(n))} of ${Ks(e,"graphic")}`:`Show ${Ks(e,"graphic")}`}function pR(e){const t=Math.max(0,Math.floor(e));return t===1?"Show all 1 graphic":`Show all ${t} graphics`}const ty="supplement",ny=1,ry=["ready","resize","error","pong"],sy=["resize","error","pong"],iy=64,fo=300,hR=5e3,mR=2e4;function gR(e,t){if(!e||typeof e!="object")return null;const n=e;if(n.lo!==ty||n.v!==ny)return null;const r=n.t;if(typeof r!="string"||!ry.includes(r))return null;const s=r;if(sy.includes(s)&&(!t||t.length>iy||n.n!==t))return null;if(s==="error"){const i=n.msg;if(typeof i!="string"||i.length>fo)return null}if(s==="resize"){const i=n.h;if(typeof i!="number"||!Number.isFinite(i)||i<0)return null}return{lo:"supplement",v:1,t:s,...typeof n.n=="string"?{n:n.n}:{},...typeof n.h=="number"?{h:n.h}:{},...typeof n.msg=="string"?{msg:n.msg}:{}}}function yR(){const e=new Uint8Array(16);crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}const oy=["--lo-accent","--lo-accent-wash","--lo-border-control","--lo-canvas","--lo-danger","--lo-hairline","--lo-info","--lo-ink","--lo-ink-dim","--lo-ink-muted","--lo-success","--lo-sunken","--lo-surface","--lo-warning","--font-mono","--font-sans"],ay=120;function cy(e=typeof document>"u"?null:document.documentElement){if(!e||typeof getComputedStyle!="function")return{mode:"dark",vars:{}};const t=getComputedStyle(e),n={};for(const s of oy){const i=t.getPropertyValue(s).trim();i&&(n[s]=i.slice(0,ay))}return{mode:e.classList.contains("dark")?"dark":"light",vars:n}}function _R(e){if(typeof MutationObserver>"u"||typeof document>"u")return()=>{};const t=new MutationObserver(()=>e(cy()));return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class"]}),()=>t.disconnect()}function vR(e){return`data:text/html;base64,${ly(e)}`}function ly(e){const t=dy(e),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let s=0;s<t.length;s+=3){const i=t[s]??0,a=t[s+1]??0,c=t[s+2]??0;r+=n[i>>2],r+=n[(i&3)<<4|a>>4],r+=s+1<t.length?n[(a&15)<<2|c>>6]:"=",r+=s+2<t.length?n[c&63]:"="}return r}function dy(e){const t=[];for(const n of e){const r=n.codePointAt(0)??0;r<=127?t.push(r):r<=2047?t.push(192|r>>6,128|r&63):r<=65535?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return t}function bR(e){return Math.min(480,Math.round(.4*Math.max(0,e)))}function uy(e){return Math.min(lo,Math.max(ns,e.heightHint))}function fy(e){return Math.min(lo,Math.max(ns,e))}function wR(e,t,n){let r=0;const s=[];for(let i=0;i<e.length;i+=1){const a=e[i],c=n?.get(a.attachment),l=c!==void 0?fy(c):uy(a);if(i>0&&(!s.every(u=>n?.get(u.attachment)!==void 0)||r+l>t))break;r+=l,s.push(a)}return{visible:s,hidden:e.slice(s.length)}}const py=/^[a-z][a-z0-9-]*\/[a-zA-Z0-9._:/-]{1,160}$/,ld=/^turn \d{1,2}: ProviderError status=(?:None|[1-5]\d{2}) kind=(?:auth|quota|transient|timeout|request|content|context|unknown)$/,hy=/kind=(auth|quota)\b/,my=/kind=(transient|timeout)\b/;function dd(e){const t=a=>typeof a=="string"&&py.test(a)&&!a.includes("://")?a:"",n=t(e.model),r=Array.isArray(e.attempts)?e.attempts.map(t).filter(Boolean).slice(0,8):void 0,s=Array.isArray(e.detail)?e.detail.filter(a=>typeof a=="string"&&(ld.test(a)||a==="prepared:unsupported")).slice(0,8):void 0,i=typeof e.cause=="string"?e.cause.slice(0,Xg):"";return{...n?{model:n}:{},...r?{attempts:r}:{},...s?{detail:s}:{},...i?{cause:i}:{}}}function SR(e){if(!ld.exec(e))return"";const n=e.split(" "),r=n[1].replace(":",""),s=n[3].slice(7),i=n[4].slice(5);return`Attempt ${r}: ${i}${s==="None"?"":` (HTTP ${s})`}`}function kR(e){const t=e.error==="generator:ProviderError"?e.detail?.at(-1)??"":"";return hy.test(t)?"The highlights model is unavailable right now. Your answer and files are unchanged.":my.test(t)?"The highlights service did not respond. Your answer and files are unchanged.":e.error==="bound:cost"?"Highlights stopped at the spending limit or unavailable pricing. Your answer and files are unchanged.":e.error==="bound:time"?"Highlights reached the time limit. Your answer and files are unchanged.":"Your answer and files are unchanged. You can retry the highlights."}function gy(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");return ud(n)?{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,...n==="decided"||n==="done"?{files:id(e.files)}:{},...n==="done"?{components:od(e.components),sounds:ad(e.sounds)}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,fo)}:{},...dd(e),live:!fd(n)}:null}function yy(e){const t=typeof e.anchor=="string"?e.anchor:"";if(!t)return null;const n=String(e.state??"");if(!ud(n))return null;const r=typeof e.files_more=="number"&&Number.isInteger(e.files_more)&&e.files_more>=0?e.files_more:0,s=Array.isArray(e.more)?e.more.filter(a=>typeof a=="string").slice(0,Hg):[];return{anchor:t,job:typeof e.job=="string"?e.job:"",version:typeof e.version=="number"&&Number.isInteger(e.version)?e.version:0,state:n,files:id(e.files),filesMore:r,more:s,components:od(e.components),sounds:ad(e.sounds),...dd(e),...e.dismissed===!0?{dismissed:!0}:{},...typeof e.error=="string"&&e.error?{error:e.error.slice(0,fo)}:{}}}function sc(e,t,n){const r=yy(t);if(!r)return null;const s=n&&n.kind==="supplement"&&n.anchor===r.anchor?n:null;return pd(s,r,e)}function ud(e){return e==="decided"||e==="queued"||e==="running"||e==="cancelling"||e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function fd(e){return e==="done"||e==="failed"||e==="cancelled"||e==="skipped"}function _y(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.path===s.path&&n.name===s.name&&n.kind===s.kind&&n.sizeBytes===s.sizeBytes&&n.mtime===s.mtime&&n.why===s.why})}function vy(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.title===s.title&&n.source===s.source&&n.mime===s.mime&&n.heightHint===s.heightHint})}function by(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.attachment===s.attachment&&n.mime===s.mime&&n.title===s.title&&n.durationS===s.durationS})}function pd(e,t,n){if(e&&(t.version<e.version||t.version===e.version&&rc(t.state)<rc(e.state)))return null;const r=!e||t.version>e.version,s=t.files!==void 0?t.files:e?.files??[],i=t.components!==void 0?t.components:e?.components??[],a=t.sounds!==void 0?t.sounds:e?.sounds??[],c=t.filesMore!==void 0?t.filesMore:e?.filesMore??0,l=t.more!==void 0?t.more:e?.more??[],d=t.error??(r?"":e?.error??""),u=t.cause??(r?"":e?.cause??""),f=t.dismissed??(r?!1:e?.dismissed??!1),p=t.live!==void 0?t.live===!0?!0:fd(t.state)?!1:e?.live??!1:e?.live??!1;return{kind:"supplement",id:uo(t.anchor),ts:e?.ts??n,anchor:t.anchor,job:t.job||e?.job||"",version:t.version,state:t.state,files:_y(s,e?.files??[])?e?.files??[]:s,filesMore:c,more:wy(l,e?.more??[])?e?.more??[]:l,components:vy(i,e?.components??[])?e?.components??[]:i,sounds:by(a,e?.sounds??[])?e?.sounds??[]:a,error:d,cause:u,model:t.model??(r?"":e?.model??""),attempts:t.attempts??(r?[]:e?.attempts??[]),detail:t.detail??(r?[]:e?.detail??[]),dismissed:f,live:p}}function wy(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>n===t[r])}const RR=e=>e.kind===void 0||e.kind==="image",st={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map};function hd(e){return e==="skipped"||e==="aborted"}function ic(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function oc(e,t,n,r){return ic(n.args)??(r?.kind==="tool"?r.args:null)??ic(e.argsByCall.get(t)?.arguments)}function md(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function gd(e){if(!e)return null;const t=e.kind;return t!=="image"&&t!=="video"&&t!=="audio"?null:typeof e.content_type=="string"||typeof e.attachment=="string"||typeof e.source_url=="string"?t:null}function Lr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!md(n)&&gd(n)===null).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function Zt(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Vn;const s=[];for(const i of r){const a=gd(i);if(i.type==="document"||a===null&&!md(i))continue;const c={id:`${t}:${s.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.content_type=="string"&&i.content_type||typeof i.mime_type=="string"&&i.mime_type||"image/png"};a!==null&&(c.kind=a,c.width=Lr(i.width),c.height=Lr(i.height),c.sizeBytes=Lr(i.size_bytes),c.durationS=Lr(i.duration_s),c.name=typeof i.name=="string"&&i.name?i.name:null,c.sourceUrl=typeof i.source_url=="string"&&i.source_url?i.source_url:null),s.push(c)}return s.length===0?Vn:n&&po(n,s)?n:s}const Vn=[],Ii=[];function Sy(e,t,n){const r=e?.content;if(!Array.isArray(r))return n?.length?n:Ii;const s=[];for(const i of r){const a=typeof i.filename=="string"&&typeof i.mime_type=="string"&&typeof i.attachment=="string"&&i.type===void 0;i.type!=="document"&&!a||s.push({id:`${t}:doc:${s.length}`,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,filename:typeof i.filename=="string"&&i.filename?i.filename:i.name??"Attached file",mimeType:i.mime_type??"application/octet-stream",path:typeof i.path=="string"&&i.path?i.path:null,storedPath:typeof i.stored_path=="string"&&i.stored_path?i.stored_path:null,bytes:typeof i.bytes=="number"?i.bytes:0,...i.injection?{injection:i.injection}:{}})}return s.length===0?n?.length?n:Ii:n&&ky(n,s)?n:s}function ky(e,t){return e.length!==t.length?!1:e.every((n,r)=>{const s=t[r];return n.id===s.id&&n.attachment===s.attachment&&n.filename===s.filename&&n.mimeType===s.mimeType&&n.path===s.path&&n.storedPath===s.storedPath&&n.bytes===s.bytes&&n.injection===s.injection})}function ac(e){let t=0;for(const n of e)n.kind!==void 0&&(t+=1),n.width!=null&&(t+=1),n.height!=null&&(t+=1),n.sizeBytes!=null&&(t+=1),n.durationS!=null&&(t+=1),n.name!=null&&(t+=1),n.sourceUrl!=null&&(t+=1);return t}function yd(e,t,n){if(t.length===0)return e;if(e.length===0||po(e,t))return t;const r=ac(e),s=ac(t);return r!==s?r>s?e:t:n==="incoming"?e:t}function Ry(e,t){return yd(e,t,"incoming")}function po(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||e[n].kind!==t[n].kind||e[n].width!==t[n].width||e[n].height!==t[n].height||e[n].sizeBytes!==t[n].sizeBytes||e[n].durationS!==t[n].durationS||e[n].name!==t[n].name||e[n].sourceUrl!==t[n].sourceUrl)return!1;return!0}function Ke(e){const t=new Map;return e.forEach((n,r)=>t.set(n.id,r)),t}function Ey(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const kt=new Set;function ho(e){return e.kind==="user"&&e.provisional===!0}function _d(e){let t=Number.POSITIVE_INFINITY;return e.forEach((n,r)=>{ho(n)&&r<t&&(t=r)}),t}function ur(e,t=kt,n){if(n?.journalMode)return Dl(n,e).map(sd);const r=e.map((a,c)=>({record:a,position:c})),s=_d(e),i=a=>ho(a.record)||a.position>s&&!t.has(a.record.id);return r.sort((a,c)=>{const l=i(a),d=i(c);return l!==d?l?1:-1:l?a.position-c.position:a.record.ts!==c.record.ts?a.record.ts-c.record.ts:a.position-c.position}).map(a=>a.record)}function Iy(e,t,n){if(!n||t<=0)return kt;let r=null;for(const s of e){if(!ho(s)||!(t>s.ts))continue;let i=!1,a=!1;for(const c of e)if(c.ts>s.ts?i=!0:c.ts<s.ts&&_o(c)&&(a=!0),i&&a)break;i&&a&&(r??=new Set,r.add(s.id))}return r??kt}function xy(e){const{provisional:t,...n}=e;return n}function xi(e,t){const n=e,r=t,s=Object.keys(n);if(s.length!==Object.keys(r).length)return!1;for(const i of s)if(n[i]!==r[i]){if(i==="images"){const a=n[i],c=r[i];if(Array.isArray(a)&&Array.isArray(c)&&po(a,c))continue}if(i==="frame"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&a.epoch===c.epoch&&a.seq===c.seq)continue}if(i==="skill"){const a=n[i],c=r[i];if(a!==void 0&&c!==void 0&&Ty(a,c))continue}return!1}return!0}function Ty(e,t){return e.name===t.name&&e.token===t.token&&e.request===t.request&&e.purpose===t.purpose&&e.body===t.body}function ge(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(xi(i,t))return e;const a=e.records.slice();if(a[n]=e.journalMode?{...t,...i.sourceEntryId?{sourceEntryId:t.sourceEntryId??i.sourceEntryId}:{},...i.sourceAdmissionAnchor&&!t.sourceAdmissionAnchor?{sourceAdmissionAnchor:i.sourceAdmissionAnchor}:{},...i.journalGeneration?{journalGeneration:t.journalGeneration??i.journalGeneration,journalSeq:t.journalSeq??i.journalSeq}:{}}:t,!e.journalMode)return{...e,records:a};const c=ur(a,kt,e);return{...e,records:c,index:Ke(c)}}const r=e.journalMode?ur([...e.records,t],kt,e):[...e.records,t],s=Ke(r);return{...e,records:r,index:s}}function mo(e,t){if(!e.records.some(t))return e;const n=e.records.filter(r=>!t(r));return{...e,records:n,index:Ke(n)}}function Ys(e,t){const n=`tool:${t}`,r=e.index.get(n);if(r===void 0)return e;const s=e.records[r];return s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")?mo(e,i=>i.id===n):e}function Cy(e,t,n){const r=e.index.get(`tool:${t}`);if(r===void 0)return e;const s=e.records[r];if(!(s.kind==="tool"&&(s.phase==="composing"||s.phase==="queued")))return e;const i=e.records.slice();return i[r]=n,{...e,records:i,index:Ke(i)}}const Ay=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function vd(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 Oy(e,t){const n=yc(e),r=yc(t);return n===r?`Context compacted to ${r} tokens`:`Context compacted, ${n} to ${r} tokens`}const bd="Context compacted",Py=12e4;function wd(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 r=new Set,s=new Set,i=new Map,a=(d,u)=>{r.add(u.id),s.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=>!r.has(f.id)&&f.before===d.before);u&&a(d,u)}const l=[];for(const d of c)if(!s.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>Py||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)s.has(d.id)||r.has(u.id)||a(d,u);return s.size===0?e:e.filter(d=>!s.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 jy(e){const t=wd(e.records);return t===e.records?e:{...e,records:t,index:Ke(t)}}const My="peer_message",Dy="ask_response",Ny="ask_timeout",Sd="Completed — runtime retired/disposed",kd="Retired for an update — a turn was in flight and was cut; its earlier output is kept",Ly="wake_prompt",$y="session_mcp_unavailable",Uy=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),Fy=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,cc=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,By=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."]),Rd=/^\[[^\]]{1,32}\]\s*/,ss="Reason:",Gy=/[\n;,(]| [—–] /,Hy=/^\d+\.$/,Wy=/[A-Z]/,zy=/\s/,Kn=160;function Wr(e,t,n){if(e==="audio_settle_v1")return{level:"info",headline:t,detail:null,category:"Audio settlement",provider:null};if(e==="session_incident")return{level:"error",...Qy(t,n)};let r;return e===$y?r=Zy(t):Uy.has(e)?r=Ky(t.trim().replace(Rd,"")):r=Jy(t),{level:"info",category:null,provider:null,...r}}function Zy(e){const t=e.trim().replace(Rd,"").split(`
|
|
27
27
|
`).map(c=>c.trim()),n=t[0]??"",r=t[1]?.startsWith(ss)?t[1]:null,s=t.slice(r?2:1).filter(Boolean).join(`
|
|
28
28
|
`),i=(r?`${n} ${r}`:n).trim();if(i.length<=Kn)return{headline:i,detail:s||null};const a=r===null?null:Vy(r);if(a!==null){const c=(f,p)=>`${ss} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,s].filter(Boolean).join(`
|
|
29
29
|
`)||null,d=`${n} ${c(a.leading,a.clause)}`;if(d.length<=Kn)return{headline:d,detail:l(a.rest)};const u=`${n} ${c("",a.clause)}`;if(u.length<=Kn)return{headline:u,detail:l([a.leading,a.rest].filter(Boolean).join(" "))}}return{headline:Id(i),detail:[r,s].filter(Boolean).join(`
|
|
@@ -31,13 +31,13 @@ Make concrete progress with the tools available, then briefly state what advance
|
|
|
31
31
|
`),r=n[0].match(Fy),i=(typeof t.raw=="string"?t.raw.trim():"")||(r?n[0].slice(r[0].length):n[0]).trim()||e.trim(),a=n.slice(1).join(`
|
|
32
32
|
`).trim();return{provider:(r?.[1]??"").trim()||null,category:(r?.[2]??"").trim()||null,headline:i,detail:a||null}}function Ed(e){if(typeof e!="object"||e===null)return null;const t=e.hub_receipt;if(typeof t!="object"||t===null)return null;const n=t,r=n.direction;if(r!=="to_child"&&r!=="to_parent")return null;const s=n.body;if(typeof s!="string"||!s.trim())return null;const i={...n};for(const a of["expects_reply","steer"])typeof i[a]!="boolean"&&(i[a]=null);for(const a of["label","job_id"])a in i&&typeof i[a]!="string"&&delete i[a];return i}function Jy(e){const t=Xy(e),n=e.split(`
|
|
33
33
|
`).map(r=>r.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Xy(e){const t=e.split(`
|
|
34
|
-
`).map(c=>c.trim()).filter(Boolean),n=c=>!cc.test(c)&&!qy(c),r=t.find(n),s=t.find(c=>cc.test(c)&&!c.startsWith("</"));let i=r??s??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return Id(i)}function qy(e){return By.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Id(e){const t=e.trim();if(t.length<=Kn)return t;const n=t.slice(0,Kn),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const e_="harness_injected",xd=e=>!e||typeof e!="object"?!1:e[e_]===!0;function Td(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Cd(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const t_="ask";function lc(e,t){return t===!0&&String(e??"")===t_}function Ad(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:bd,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=vd(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Sd,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:kd,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Ei){const a=n.details??{};return sc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(Ay.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Si(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Zs(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Wr(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Zt(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===My){const{body:u,sender:f}=Vl(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Zs(t.sender,f)?t.sender:f}}if(a===Ly){if(qm(c)||eg(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===Dy){const u=c.answers,f={};if(u&&typeof u=="object")for(const[g,m]of Object.entries(u))f[String(g)]=Array.isArray(m)?m.map(y=>String(y)):[];const p=c.questions,h=Array.isArray(p)?p.flatMap(g=>{if(!g||typeof g!="object")return[];const m=g;return[{id:String(m.id??""),question:String(m.question??""),secret:m.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:h,answers:f,secretLost:c.secret_lost===!0}}if(a===Ny){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Ei)return sc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Bg(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,attribution:n.attribution??"system",...Wr(a,d,c)}:null}const i=String(n.role??"");if(i==="user"){const a=Ed(n.provider_payload);if(a){const u=Si({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Zs(f.sender,u.sender)&&(u.sender=f.sender);const p=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Wr("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Zt(n,e.id,p)}}}if(xd(n.provider_payload))return null;const c=ft(n);if(rd(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=ms(c),d=Sy(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Zt(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Cd(l))return null;const d=hd(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Zt(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...nd(c.details,t?.kind==="tool"?t:null),diff:td(ed(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Kl(c.details,t?.kind==="tool"?t.delivery:null),details:ki(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function n_(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}const r_=/^(?:tool|compaction|local):/;function s_(e){for(const t of e.records){switch(t.kind){case"user":case"assistant":case"custom":case"peer":case"wake":case"compaction":case"ask_response":case"ask_timeout":break;default:continue}if(!(t.kind==="user"&&t.local)&&!r_.test(t.id))return t.id}return null}function i_(e,t){const n=Wg(t);if(n)return e.records[e.index.get(n)??-1]}function go(e){const t=Dl(e,e.records);if(t===e.records)return e;const n=t.map(sd);return{...e,records:n,index:Ke(n)}}const fr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Od(e,t,n,r){const s={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:i,local:a,...c}=s;return c}return s}function o_(e){const t=new Set,n=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s!="string"||s.length<1||s.length>128||(t.add(s),r.journalGeneration===e.journalGeneration&&fr(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function yo(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function dc(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const s=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=yo(a);return l!==a&&(r=!0),l});let i=r?{...e,records:s}:e;return i=Pd(i,n),i}function Pd(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=o_(e),s=e.orderRevision??0,i=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(i??[])),a.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function is(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const s=r.journalBodyOwed;let i=null;const a=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(i||(i=new Map(s)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?r:{...r,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function br(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function jd(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function a_(e,t,n){let r=Rn(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)r=so(r,{...i.payload,id:i.id});const s=br(r,!1);return go(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function uc(e,t,n){let r=Rn(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=br(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(r=Pd(r,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=is(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=jd(r,t),go(r)}function c_(e,t,n,r){let s=Rn(e,t,[],!1,n,{peer:!0});s=br(s,!0);const i=s.journalBodyOwed,a=h=>r!==void 0&&(i?.get(h)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===s.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=s.records,f=s.index;if(l.length>0){const h=new Map;for(const g of l){if(typeof g.id!="string"||g.id===""||a(g.id))continue;const m=`tool:${String(g.payload?.tool_call_id??"")}`,y=f.get(g.id)??f.get(m),_=y===void 0?void 0:u[y];if(!_)continue;let b=Ad(g,_);b&&(b={...b,sourceEntryId:g.id},fr(g.journal_seq)?(b=Od(b,g.id,t.journal_generation,g.journal_seq),d.push(g.id)):b=yo(b),h.set(_.id,b))}h.size>0&&(u=u.map(g=>h.get(g.id)??g),f=Ke(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=is(p,d,!1);const h=(t.source_missing_ids??[]).filter(g=>typeof g=="string"&&g.length>0&&g.length<=128&&!a(g));if(h.length>0){p=is(p,h,!1);const g=new Set(p.journalSourceVoid??[]);for(const m of h)g.add(m);p={...p,journalSourceVoid:g}}}return p=jd(p,t),go(p)}function $r(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Yn(e,t,n={}){let r=e;const s=r,i=[],a=x=>br(is(x,i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Rn(r,t,t.entries.map(x=>({id:x.id,journal_seq:x.journal_seq,role:x.payload?.role,tool_call_id:x.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const x of t.entries)r=so(r,{...x.payload,id:x.id});const l=n.keepPaging===!0&&r.viewEpoch>0,d=[];for(const x of t.entries){if(l&&!I_(x,r.clearedAt))continue;const C=r.records[r.index.get(x.id)??-1]??r.records[r.index.get(`tool:${String(x.payload?.tool_call_id??"")}`)??-1]??i_(r,x);let re=Ad(x,C);re&&r.journalMode&&(re={...re,sourceEntryId:x.id}),re&&c&&fr(x.journal_seq)?(re=Od(re,x.id,t.journal_generation,x.journal_seq),i.push(x.id)):re&&n.peerSource===!0&&(re=yo(re)),re&&d.push(re)}let u=r.argsByCall,f=!1;for(const x of t.entries){const C=x.payload?.tool_calls;if(!Array.isArray(C))continue;const re=Math.round((x.ts??0)*1e3);for(const je of C)!je||typeof je.id!="string"||u.has(je.id)||(f||(u=new Map(u),f=!0),u.set(je.id,{...je,anchoredAt:re,anchorId:x.id}))}for(let x=0;x<d.length;x++){const C=d[x];if(C.kind!=="tool")continue;const re=u.get(C.toolCallId);if(!re)continue;const je=re.arguments??null;d[x]={...C,args:je,intent:typeof je?.i=="string"?je.i:null}}const p=f?r.records.map(x=>{if(x.kind!=="tool"||x.args)return x;const re=u.get(x.toolCallId)?.arguments??null;return re?{...x,args:re,intent:x.intent??(typeof re.i=="string"?re.i:null)}:x}):r.records,h=new Set(t.entries.map(x=>x.id)),g=n.peerSource===!0&&n.replace===!0?r.records.filter(x=>x.kind==="user"&&(x.provisional===!0||x.local===!0)&&!h.has(x.id)):[],m=n.replace?g.length>0?{...st,records:g,index:Ke(g)}:st:{...r,records:p},y=new Map(m.records.map(x=>[x.id,x]));let _=r!==s||n.replace||!n.replace&&p!==r.records;for(const x of d){const C=y.get(x.id);if(!C){_=!0,y.set(x.id,x);continue}if(C.kind==="tool"&&x.kind==="tool"){const re={...x,args:x.args??C.args,intent:x.intent??C.intent,images:yd(x.images,C.images,"current")};xi(C,re)||(_=!0,y.set(x.id,re));continue}xi(C,x)||(_=!0,y.set(x.id,x))}const b=r.compacting&&t.entries.some(x=>r.index.has(x.id)||Math.round((x.ts??0)*1e3)<r.compactingSince?!1:x.type==="compaction"||x.type==="message"&&x.payload?.custom_type==="compaction_refused"),R=t.entries[0],M=R?Math.round((R.ts??0)*1e3):0,G=r.journalMode?kt:Iy(m.records,M,n.statedByOwner!==!1);let A=m.oldestId,O=m.oldestTs,S=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(R&&(A=R.id,O=M),S=t.has_more):n.pagedBefore!==void 0?R?(A=R.id,O=M,S=t.has_more):S=!1:R&&(r.journalMode?(r.journalPositions?.get(R.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):M>0&&M<r.oldestTs)&&(A=R.id,O=M,S=t.has_more));const U=A!==r.oldestId||O!==r.oldestTs;if(!_&&!U&&r.hasMore===S&&!b&&G.size===0)return a(r);const V=G.size===0?[...y.values()]:[...y.values()].map(x=>G.has(x.id)?xy(x):x),ce=wd(ur(V,n.statedByOwner===!1?kt:new Set(d.map(x=>x.id)),r));return n.keepPaging?a({...r,records:ce,index:Ke(ce),argsByCall:u}):a({...r,records:ce,index:Ke(ce),oldestId:A,oldestTs:O,hasMore:S,argsByCall:u,compacting:b?!1:r.compacting,compactingSince:b?0:r.compactingSince})}const l_=/^(?:local|notice|retry|subagent|compaction):/;function _o(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!l_.test(e.id)}}function d_(e,t,n=kt){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&_o(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Ke(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const _t={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Qs(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ti(e,t,n=Date.now(),r={}){let s=e;const i=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(s={...s,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return s;const d=Rn(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=ur(d.records,kt,d);return d===s&&u===s.records?s:{...d,records:u,index:Ke(u)}}i&&(s=so(s,i));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??s.generation+1);return l===s.generation?s:{...s,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return s.compacting?s:{...s,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??s.generation)<s.generation)return s;let d=s;for(const u of s.records)if(u.kind==="assistant"&&u.streaming&&(d=ge(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=ge(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Qs(i);if(i===void 0||l===null)return _t.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(i.role==="user"){const u=Ed(i.provider_payload);if(u){const g=ft(i),m=Si({...u,text:g});if(m.body.trim()){const y=d?.kind==="user"&&d.provisional===!0;return ge(s,{kind:"custom",id:l,ts:y?os(s,n):n,customType:"hub_message",text:m.envelope,attribution:"user",...Wr("hub_message",m.envelope||m.body,{...u}),receipt:m,images:Zt(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(xd(i.provider_payload))return s;const f=ft(i);if(rd(f))return s;const p=d?.kind==="user"&&d.provisional===!0,h=ms(f);return ge(s,{kind:"user",id:l,ts:p?os(s,n):n,text:f,images:Zt(i,l,d?.kind==="user"?d.images:void 0),...p?{provisional:!0}:{},...h?{skill:h}:{}})}return i.role!=="assistant"||d?s:ge(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Qs(i);if(i===void 0||l===null)return _t.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=ft(i);if(d===void 0)return!f&&!u?s:ge(s,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const p=s.records[d];if(p.kind!=="assistant")return s;if(!p.streaming)return _t.settledAssistantUpdate+=1,s;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return _t.staleUpdateFrameDropped+=1,s;const h=Ey(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?s:(_t.seededDeltaWithheld+=p.text?1:0,ge(s,{...p,text:p.text||u,...h?{frame:h}:{},truncated:p.text?"interrupted":"prefix"}));let g;if(f){if(g=f+u,g.length<=p.text.length)return s}else{if(!u)return s;g=p.text+u}return ge(s,{...p,text:g,...h?{frame:h}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=Qs(i);if(i===void 0)return _t.idlessFrameRefused+=1,s;if(l===null){if(i.role!=="assistant")return _t.idlessFrameRefused+=1,s;let g;for(const _ of s.records)if(!(_.kind!=="assistant"||!_.streaming)){if(g!==void 0)return _t.idlessFrameRefused+=1,s;g=_}if(g===void 0)return _t.idlessFrameRefused+=1,s;const m=Array.isArray(i.tool_calls)?i.tool_calls:[],y={...g,streaming:!1,settledAt:g.settledAt??n,callsTools:m.length>0,...g.text||m.length===0?{complete:!0}:{}};return ge(s,y)}if(i.role!=="assistant")return s;const d=s.index.get(l),u=ft(i),f=d===void 0?void 0:s.records[d],p=Array.isArray(i.tool_calls)?i.tool_calls:[],h={kind:"assistant",id:l,ts:d===void 0?n:s.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:i.stop_reason??null,error:!!i.is_error};return ge(s,h)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(R=>String(R.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,p=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,h="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,g=s.journalPeerSource===!0||h,m=g&&u!==void 0&&u===s.journalGeneration,y=d.map(R=>String(R.id??"")).filter(R=>R.length>0&&R.length<=128),_={entries:d.map(R=>{const M=String(R.id??""),G=f?.[M],A=p?.[M];return{id:M,ts:m&&typeof A=="number"&&Number.isFinite(A)?A:n/1e3,type:"message",payload:{kind:R.custom_type?"custom":"message",...R},...m&&fr(G)?{journal_seq:G}:{}}}),has_more:s.hasMore,...m?{journal_generation:u}:{}};let b=Yn(s,_,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:g});if(g&&y.length>0)if(m){const R=y.filter(M=>!fr(f?.[M]));R.length>0&&(b=dc(b,R))}else b=dc(b,y),u!==void 0&&(b=Rn(b,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),b=br(b,!0));return b}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return s;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=s.records[s.index.get(u)??-1],p=d?s.records[s.index.get(`tool:${d}`)??-1]:void 0,h=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(h&&h.phase!=="composing"&&h.phase!=="queued")return d&&f?.kind==="tool"?Ys(s,d):s;const m=String(t.not_run_reason??"").trim()||null,y=String(t.not_run_kind??"").trim()||null;if(lc(t.tool_name,c)&&!m&&!h)return d?Ys(s,d):s;const _=Number(t.argument_bytes??0),b={kind:"tool",id:u,ts:h?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:m?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:_>0?_:h?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Vn,added:0,removed:0,diff:null,stopped:!1,notRunReason:m,notRunKind:m?y:null,neverSent:m!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Cy(s,d,b):ge(d&&f?.kind==="tool"?Ys(s,d):s,b)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return s;const f=oc(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:_n(t)??n}):s.argsByCall,h=p===s.argsByCall?s:{...s,argsByCall:p};return lc(t.tool_name,c)&&!u?h:ge(h,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:_n(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Vn,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(!u||u.kind!=="tool")return s;const f=t.partial_result??{},p=ki(f.details,u.details);return p===(u.details??null)?s:ge(s,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1],f=t.result??{};if(Cd(f.details))return Nd(s,d);const p=oc(s,l,t,u),h=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,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:Vn,added:0,removed:0,diff:null,stopped:!1},g=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:_n(t)??n}):s.argsByCall,m=g===s.argsByCall?s:{...s,argsByCall:g},y=r.userStoppedAt??null,_=!!(t.is_error??f.is_error),b=hd(f.details?.__fault),R=y!==null&&(typeof h.startedAt=="number"?h.startedAt<=y:_);return ge(m,{...h,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:R||b?!1:_,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof h.startedAt=="number"?h.startedAt+t.duration_s*1e3:null,startedAt:null,images:Ry(Zt(f,d,h.images),h.images),...nd(f.details,h),diff:td(ed(f.details),h.diff),stopped:h.stopped||R||b,delivery:Kl(f.details,h.delivery),details:ki(f.details,h.details)})}case"supplement_progress":{const l=gy(t);if(!l)return s;const d=uo(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=pd(f,l,n);return p?ge(s,p):s}case"notice":{const l=String(t.text??"");if(!l)return s;const d=`notice:${s.generation}:${l}`;return s.index.has(d)?s:ge(s,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:vd(String(t.detail??"")),p=f?f.text:l&&d?Oy(l,d):bd,h=`compaction:${s.generation}:${l}:${d}`,g=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return g.index.has(h)?g:f?ge(g,{kind:"notice",id:h,ts:n,text:p,level:f.level}):jy(ge(g,{kind:"compaction",id:h,ts:n,text:p,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:ge(s,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:ge(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function _n(e){return Gh(e.started_at_epoch)}function vo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function u_(e){const t=vo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function f_(e,t){const n=_n(e);if(n!==null)return n;const r=vo(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function p_(e,t){if(_n(e)!==null)return!1;const n=vo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const s=t.index.get(r);return s!==void 0&&s<=_d(t.records)}function bo(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 gs(e){return e.type==="tool_execution_end"}function h_(e,t,n=Date.now(),r=null){let s=e;t.streaming&&t.generation>s.generation&&(s={...s,generation:t.generation}),s.compacting&&(s={...s,compacting:!1,compactingSince:0});const i=t.streaming===!0,a=Td(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const h=u_(f);if(h!==null&&!s.index.has(h)){const g=f_(f,s);if(g!==null)p=g,c=!0,p_(f,s)&&l.add(h);else if(gs(f)||bo(f)||!i)continue}s=Ti(s,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return s;const d=ur(s.records,l,s);return{...s,records:d,index:Ke(d)}}function fc(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!gs(r)&&!bo(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const i=_n(r);i!==null&&t.set(s,i)}return t}function m_(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const s=r.not_run_reason;if(typeof s=="string"&&s.trim().length>0)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}const g_=5e3;function y_(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const s of e){if(s.payload?.role!=="tool")continue;const i=s.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=s.ts;typeof a!="number"||!Number.isFinite(a)||r.set(i,Math.round(a*1e3))}return r}function __(e,t,n,r=new Map,s=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(i*1e3)<=a-g_}function pc(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!gs(s)&&!bo(s))continue;const i=String(s.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function hc(e,t,n,r){const s=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=r||s.push(a)));return s}const v_=3.25,Ci=100,wo=500;function mc(e){return e<=0?Ci:Math.min(wo,Ci+Math.ceil(v_*e))}function Js(e,t){const n=[];if(t.size===0)return n;for(const r of e){const s=r.payload?.tool_calls;if(Array.isArray(s))for(const i of s)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function b_(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function w_(e,t){const n=new Set(t);for(const i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],s=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||s.has(a)||(s.add(a),r.push(a))}return r}function S_(e,t){return e&&t===0}function k_(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,i=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!gs(r)&&!i)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Md(e,t,n){const r=new Set(e),s=[];for(const i of t)!r.has(i)&&!n.has(i)&&s.push(i);for(const i of e){if(n.has(i))return s;t.has(i)&&s.push(i)}return s}function R_(e,t,n){return Md(e,t,n).length}function gc(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=ge(t,{...n,truncated:"interrupted"}));return t}function E_(e,t=Date.now()){return e.records.length===0?e:{...st,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function I_(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 yc(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function x_(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return mo(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function os(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Dd(e,t,n,r,s=Date.now(),i=Ii){if(e.index.has(t))return e;const a=ms(n);return ge(e,{kind:"user",id:t,ts:os(e,s),text:n,images:r,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Nd(e,t){return mo(e,n=>n.id===t)}let _c=0;function T_(e,t,n,r=Date.now()){return _c+=1,ge(e,{kind:"notice",id:`local:${r}:${_c}`,ts:os(e,r),text:t,level:n})}function RR(e,t,n,r){const s=t?.anchor_id,i=t?.kind;return!s||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),ge(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?Sd:i==="retired"?kd:i==="error"?"Stopped with an error":"Interrupted",level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"}))}const C_="compacting context…";function ER(e){return typeof e=="string"&&e.trim()===C_}const A_=[1500,5e3];async function IR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of A_){await t(n);try{if(await e())return}catch{}}}function O_(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 vc=new Set(["openrouter","radient","radient-key"]),P_=new Set(["auto","openrouter/auto"]),j_="Auto";function Ld(e){return e.slice(e.lastIndexOf("/")+1)||e}function M_(e,t){return e===t||e===Ld(t)}function Xs(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 xR(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,r=typeof e.display_name=="string"?e.display_name.trim():"",s=vc.has(t)||!r||M_(r,e.model_id)||r.toLowerCase()==="unknown";return{name:vc.has(t)&&P_.has(e.model_id)?j_:s?Ld(n):r,selector:n}}function TR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function CR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function AR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function OR(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 PR(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const s=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${r.get(l)}`)}function jR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function MR(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 $d(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 DR(e,t){const n=(e??t)?.effective_model;return $d(n)?null:n?.model_id??null}function NR(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,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=$d(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${r?` (${r})`:""}. It offers ${n.join(", ")}.`}:s?{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&&r?{label:r,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 LR(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:`Reasoning effort. This model offers ${n.join(", ")}.`}}function D_(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Ln(n.provider);if(!a)return null;const c=Ln(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Ln(n.label)||a,effectiveState:d,owner:Ln(n.owner_label)||Ln(n.owner_device)||"the owner device",observedAt:qs(n.observed_at),lastGrantAt:qs(n.last_grant_at),lastGrantExpiresAt:qs(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const s=e?.effective_model?.provider;if(s&&s!==r)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:i,state:n.state}:{provider:r,label:i}}function $R(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function UR(e){return e&&e.draft!==!0?D_(e.frontend,e.servingLocality):null}function Ln(e){return typeof e=="string"?e.trim():""}function qs(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ei(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function FR(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",s={local:[`${t} access available`,"This session uses its own provider access."],pending:[`Checking ${t} access`,"Access has not converged yet. The next request checks the owner automatically; no additional sign-in is needed here."],eligible_borrow_unverified:[`Checking access from ${r}`,`This session may borrow ${t} access, but it has not resolved it yet. The next request verifies ${r} automatically.`],effective_borrow:[`${t} access from ${r}`,"The runtime resolved borrowed access for this session. Every new request checks the owner again."],expired:[`Fresh ${t} access needed`,`The last borrowed grant expired, but borrowing permission is still present. The next request asks ${r} for fresh access automatically.`],withdrawn:[`${t} access needs attention`,"The owner cannot currently provide borrowed access, or borrowing permission is unavailable. Restore owner access or permission before retrying, or choose another model."],owner_unavailable:[`${r} cannot provide access`,`This session could not resolve ${t} access from ${r}. Previous access cannot be reused. Retry after owner access is restored, or choose another model.`],device_bound:[`${t} needs a device sign-in`,"This login cannot be borrowed. Sign in on the device running this session, or choose another model."],absent:[`No ${t} access`,e.connectHere===!0?"The serving device has no effective provider access for this session. Connect an account or choose another model.":"The device running this session has no effective provider access. Sign in or restore access on that device, or choose another model."]},i=e.state==="temporarily_unavailable",[a,c]=n?s[n]:[i?`${t} is temporarily unavailable`:`Not signed in to ${t}`,i?"Your saved sign-in is still present. Try again later or choose another model.":`This session runs ${t} without a working sign-in, so it cannot answer until you connect it.`],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ei(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ei(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ei(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function BR(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function GR(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function HR(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function N_(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function L_(e,t){return!!e.streams[t]}function Ud(e,t){return e.attached[t]?.turns.at(-1)}function WR(e,t){const n=Ud(e,t);return n?e.streams[n.asideId]:void 0}function zR(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s&&e.streams[s.asideId]?.settled)return s.asideId}}function $_(){return{text:"",streaming:!0,settled:!1,error:null}}function U_(e){return{text:e,streaming:!1,settled:!0,error:null}}function F_(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const B_=vr(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(s=>({streams:{...s.streams,[n]:$_()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=N_(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:U_(n)}}:r),failAside:(t,n)=>e(r=>L_(r,t)?{streams:{...r.streams,[t]:F_(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const s=r.attached[t];return s?{attached:{...r.attached,[t]:{...s,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];return i?{attached:{...s.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];if(i?.queued?.asideId!==n)return s;const{queued:a,...c}=i;return{attached:{...s.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],s={...n.attached};if(delete s[t],!r)return{attached:s};const i={...n.streams};for(const a of r.turns)delete i[a.asideId];return{streams:i,attached:s}})}));function ZR(e,t){return Ud(e,t)?.asideId}const G_=4*1024*1024,bc=1024*1024,pt=new Map;function wc(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function H_(e){const t=e.slice(-200),n=wc(t);if(n<=bc)return{records:t,bytes:n};let r=0,s=t.length,i=0;for(;s-r>1;){const a=Math.floor((r+s)/2),c=wc(t.slice(a));c>bc?r=a:(s=a,i=c)}return{records:t.slice(s),bytes:i}}function W_(e,t){const{records:n,bytes:r}=H_(x_(t.transcript).records);if(n.length===0){pt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},i={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Sc(n,t.owedLabels),markLabels:Sc(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>s.index.has(a)))};pt.delete(e),pt.set(e,i),Z_()}function Sc(e,t){if(!t||t.size===0)return kc;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:kc}const kc=new Set;function Fd(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function z_(e){pt.delete(e)}function Z_(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>G_&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const V_=8,K_=128,Bd=new Set,Y_="",bt=new Map,So=e=>e??Y_;function VR(e){return bt.get(So(e))??Bd}function KR(e,t,n){const r=So(e),s=bt.get(r)??new Set,i=new Set(s);if(n)for(i.delete(t),i.add(t);i.size>K_;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(bt.delete(r),i.size>0&&bt.set(r,i);bt.size>V_;){const a=bt.keys().next().value;if(a===void 0)break;bt.delete(a)}return bt.get(r)??Bd}function Q_(e){bt.delete(So(e))}const J_=128,as=4096,ti=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Rc=e=>e.startsWith("qg:")&&e.length>3;function YR(e,t,n=null,r=[]){const s=new Map,i=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(s.has(u))return ti("duplicate-prior-id");if(s.size===as)return ti("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Rc(l.key)&&t.has(l.key)&&i.size<J_&&i.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===as)return ti("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:s.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&Rc(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:s,keys:i,reason:null}}function QR(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>as)return r("prior-id-limit");const s=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,h)=>{const g=a.get(f);g===void 0?a.set(f,{current:p,many:!1,lastOrder:h,reordered:!1,outside:!1}):(g.current!==p&&(g.many=!0),h<=g.lastOrder&&(g.reordered=!0),g.lastOrder=h)};for(let f=0;f<t.length;f+=1){const p=t[f];let h=null,g=!1;for(const y of p.segmentIds){if(i!==null){if(i.has(y))return r("duplicate-current-id");if(i.size===as)return r("current-uniqueness-unproved");i.add(y)}const _=e.owners.get(y);if(_!==void 0){if(s.has(y))return r("duplicate-current-id");s.add(y),l(_.ordinal,f,_.order),h===null?h=_.ordinal:h!==_.ordinal&&(g=!0)}}if(p.eligible===!1||g||h===null||h<0)continue;const m=e.keys.get(h);m!==void 0&&c.set(f,{owner:h,key:m})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const h=a.get(p.ordinal);h!==void 0&&(h.outside=!0)}for(const[f,p]of c){const h=a.get(p.owner),g=p.key.slice(3);(h===void 0||h.many||h.reordered||h.outside||!s.has(g))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const h=c.get(p);return h===void 0?f:{...f,key:h.key}}),reason:null}}const X_=8,q_="",zt=new Map,ko=e=>e??q_;function JR(e){return zt.get(ko(e))??null}function XR(e,t){const n=ko(e);for(zt.delete(n),zt.set(n,t);zt.size>X_;){const r=zt.keys().next().value;if(r===void 0)break;zt.delete(r)}}function ev(e){zt.delete(ko(e))}function tv(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===s;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing){const u=s_(n.getTranscript()),f=u!==null&&u!==a?u:n_(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==s?u:Yn(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==s||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const s=r.getTranscript();if(!s.hasMore||!s.oldestId)return Promise.resolve({kind:"nothing-to-load"});const i={key:n,promise:t(r,s.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const nv=new Set(["subagent_start","subagent_progress","subagent_end"]),rv=(e,t)=>({...e,[t]:(e[t]??0)+1}),sv=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Gd(n);r&&(t[r]=(t[r]??0)+1)}return t},Gd=e=>{if(!e||typeof e!="object")return null;const t=e;return nv.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},iv=(e,t)=>{const n=Gd(t);return n?rv(e,n):e};function Ec(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const s=t.context_tokens;return typeof s=="number"&&Number.isFinite(s)&&s>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function ov(e){for(const t of e)t.type==="aside_delta"&&B_.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function av(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Ht=new Set,Hn=new Set;function cv(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const lv=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),dv=15e3,Ai=[500,1e3,2e3,4e3,8e3,8e3],uv=Ai.length,fv=2e4,pv=1e4,hv=1e4;function Ic(e){const t=Math.max(1,Math.min(e,Ai.length));return Ai[t-1]??8e3}const mv=3,gv=250,yv=32*1024,xc=512,Tc=new Set(["turn_end","agent_end"]),Cc=2,_v=500,Ac=wo,vv=6,ni=Il("sessions.history"),bv=2e3,Oc={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Yt=new Map,zr=new Map,wv=8,Sv=2048,Pc=1024,kv=1024,Rv="",Bt=new Map;function jc(e){const t=e??Rv,n=Bt.get(t);if(n)return Bt.delete(t),Bt.set(t,n),n;const r={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(Bt.set(t,r);Bt.size>wv;){const s=Bt.keys().next().value;if(s===void 0||s===t)break;Bt.delete(s)}return r}function ri(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function si(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function Ev(e,t){return zr.set(e,t),()=>{zr.get(e)===t&&zr.delete(e)}}function qR(e){const t=zr.get(e);return t?(t(),!0):!1}const Re=new Map,Iv=4,xv=16;function Hd(e,t){e(n=>Dd(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function Tv(e,t,n){const r=e.index.get(t),s=r===void 0?void 0:e.records[r];if(r===void 0||!s||s.kind!=="user"||!s.local||s.text===n)return e;const i=e.records.slice(),{skill:a,...c}=s,l=ms(n);return i[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function Oi(e,t){let n=Re.get(e);if(!n){if(Re.size>=xv){const i=Re.keys().next();i.done||Re.delete(i.value)}n=new Map,Re.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>Iv;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const s=Yt.get(e);s&&Hd(s,r)}function eE(e){if(!e)return null;const t=Re.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function Pi(e,t){const n=Re.get(e);n&&(n.delete(t),n.size===0&&Re.delete(e))}function ji(e,t){const n=Re.get(e)?.get(t);n&&(n.settled=!0)}function Mc(e,t){return e?Re.get(e)?.has(t)===!0:!1}function tE(e){return e?(Re.get(e)?.size??0)>0:!1}function Cv(e,t,n){const r=Re.get(e)?.get(t);if(!r)return;r.text=n;const s=Yt.get(e);s&&s(i=>Tv(i,t,n))}function Av(e,t){if(e===t)return;const n=Re.get(e);if(!n)return;Re.delete(e);const r=Re.get(t)??new Map;for(const[s,i]of n)i.identity=t,r.set(s,i);Re.set(t,r)}function Ur(e){Re.delete(e)}function Ov(e,t){const n=Re.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),i=s===void 0?void 0:t.records[s];i?.kind==="user"&&i.local!==!0&&Pi(e,r)}}function Pv(e,t){Yt.set(e,t);const n=Re.get(e);if(n)for(const r of n.values())Hd(t,r);return()=>{Yt.get(e)===t&&Yt.delete(e)}}function jv(e,t){const n=Re.get(e);if(!n)return t;let r=t;for(const s of n.values())r=Dd(r,s.id,s.text,s.images);return r}function Mv(e,t,n){return e===t?!0:!n}function Dv(e,t){const n=Yt.get(e);if(!n)return Pi(e,t),"queued";let r="queued";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"?s:i.local?(r="retracted",Nd(s,t)):(r="owner",s)}),Pi(e,t),r}function Wd(e,t){const n=Yt.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"||(r=i.local?"local":"owner"),s}),r}function Nv(e){const t=Fd(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:st,stale:!1,owedLabels:Ht,markLabels:Hn}}function Lv(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function ii(e,t){if(e.size!==0)for(const n of t)e.delete(rt(n))}function Fr(e,t){for(const n of t)e.add(rt(n))}function nE(e,t,n=!0,r=e,s={}){const i=s.openFrame===!0,a=s.journalOrder===!0,c=v.useRef(a);c.current=a;const l=v.useRef(i);l.current=i;const d=s.peerJournalSource===!0,u=v.useRef(d);u.current=d;const f=v.useRef(null),p=v.useRef(0),h=v.useRef(0),g=v.useRef(0),m=v.useRef(null),y=v.useRef(null),_=v.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const T=ze.getState();return Eb(T.sessions,T.placementFacts,e)},[e]),b=v.useCallback(()=>{const T=f.current;return _()&&T!==null&&T.sessionId===e&&T.peer},[_,e]),R=v.useCallback(()=>{const T=f.current;return T!==null&&T.sessionId===e&&T.peer},[e]),[M,G]=v.useState(()=>{const T=t&&e?Nv(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?jv(r,T?.transcript??st):st,stale:T?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:T?.owedLabels??Ht,labelMarked:T?.markLabels??Hn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),A=v.useRef(M),O=v.useCallback(T=>{const K=T(A.current);return K===A.current||(A.current=K,G(K)),K},[]),S=v.useRef(e),U=v.useRef([]),V=v.useRef(st.index),ce=v.useRef(new Set),x=v.useRef(new Set),C=v.useRef(jc(e)),re=v.useRef(new Set),je=v.useRef(null),xn=v.useRef({}),Is=v.useRef(null),xs=v.useRef(null),Ts=v.useRef(null),Tn=v.useRef(0),Xe=v.useRef(0);v.useEffect(()=>{if(!e||!t)return;const T=++Xe.current,K=new WeakMap,se=(W,z)=>{const Y=K.get(W);if(Y===void 0||Ye(z)===Y.revision)return!1;const ee=W.payload.history.journal_generation;return!(typeof ee=="string"&&ee.length>0&&ee===z.journalGeneration)};let pe=null,H=!1,we=0,$e=0,ue=0,me=0,D=0,he=0,oe=0,Ee=!1;const Se=()=>{he&&(window.clearTimeout(he),he=0)},Te=W=>{for(const z of W)C.current.attempts.set(z,(C.current.attempts.get(z)??0)+1)},sn=W=>{O(z=>{const Y=new Set;for(const q of z.labelPending)z.labelPending.has(q)&&(si(C.current,z.transcript.argsByCall,q,ri(z))||Y.add(q));let ee=null;for(const q of z.labelMarked)si(C.current,z.transcript.argsByCall,q,ri(z))||(ee=ee??new Set(z.labelMarked),ee.delete(q));if(Y.size===0&&!ee)return z;const ie=new Set(z.labelPending);for(const q of Y)ie.delete(q);return{...z,labelPending:ie.size?ie:Ht,labelMarked:ee&&ee.size===0?Hn:ee??z.labelMarked}})},Zu=W=>{O(z=>{let Y=null,ee=null;for(const ie of W)z.labelPending.has(ie)&&(Y=Y??new Set(z.labelPending),Y.delete(ie),ee=ee??new Set(z.labelMarked),ee.add(ie));return!Y||!ee?z:{...z,labelPending:Y.size?Y:Ht,labelMarked:ee}})},Ir=async(W,z,Y=Oc,ee=1,ie,q=z,Be=null)=>{Tn.current+=1,Xe.current===W&&O(Ie=>Ie.historyReadPending?Ie:{...Ie,historyReadPending:!0});for(const Ie of Y.targets)C.current.inFlight.add(Ie),re.current.add(Ie);let Me=!1;try{Me=await Vu(W,z,q,Be,Y,ee,ie)}finally{if(Tn.current=Math.max(0,Tn.current-1),Tn.current===0&&O(Ie=>Ie.historyReadPending?{...Ie,historyReadPending:!1}:Ie),!Me){for(const Ie of Y.targets)C.current.inFlight.delete(Ie);C.current.refused&&Zu(Y.targets),sn()}}},Vu=async(W,z,Y,ee,ie,q,Be)=>{const Me={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:Y.size===0},Ie=A.current.transcript.viewEpoch,Ce=await Ku(W,z,Y,ee,ie,q,Me,Be);if(Ce||Xe.current!==W||Me.reachedHeld||A.current.transcript.viewEpoch!==Ie)return Ce;const Ge=z!==Y&&[...z].some(We=>Y.has(We));if(Ge&&Me.joined)return Ce;let He;if(Me.oldest){if(!Me.hasMore)return Ce;He={id:Me.oldest.id,ts:Math.round((Me.oldest.ts??0)*1e3)}}else{if(Ge||!ee)return Ce;He=ee}if(!He)return Ce;const It=O(We=>{const et=d_(We.transcript,He,Me.keys);return et===We.transcript?We:{...We,transcript:et}});return V.current=It.transcript.index,Ce},Ku=async(W,z,Y,ee,ie,q,Be,Me)=>{const Ie=A.current.transcript.viewEpoch,Ce=()=>A.current.transcript.viewEpoch!==Ie,Ge=new Set;let He,It=0,We=0,et=!1,xt=Y.size===0,on=!1;const xr=A.current.cold,tt=new Set(ie.found),lt=()=>R_(ie.order,ie.targets,tt),Tr=()=>Md(ie.order,ie.targets,tt),Ps=()=>{const $=new Map;for(const be of w){if(tt.has(be))continue;const le=fe.get(be);le!==void 0&&$.set(be,le)}return $},E=new Set(ie.every);for(const $ of tt)E.add($);const w=new Set,fe=new Map;let ve=1;const De=ie.targets.size>0;let Z=Math.max(mc(lt()),De?C.current.depth:0),jn=0;for(;It<Ac&&We<vv;){We+=1;let $;const be=wi(A.current.transcript),le=be.revision;try{$=await xe({op:"sessions.history",sessionId:e,...He?{beforeId:He}:{},limit:Math.min(Z,Ac-It),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}})}catch{if(Ce())return!1;if(A.current.transcript.records.length>0){if(jn++>0)return C.current.refused=!0,!1;continue}return q<mv?(D=window.setTimeout(()=>{if(D=0,Xe.current!==W||Ce()){sn();return}Ir(W,z,ie,q+1,Me,Y,ee)},Ic(q)),!0):(O(de=>({...de,status:"unavailable",failure:Zh,heldFrontend:null,...de.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{sn()}if(Xe.current!==W||Ce())return!1;if(Ye(A.current.transcript)!==le){if(!A.current.hydrated)continue;return!1}C.current.refused=!1;const nt=$.entries[0];It+=$.entries.length,Me?.($.entries.length),ii(ce.current,$.entries),Fr(x.current,$.entries),O(de=>{if(Ye(de.transcript)!==le)return de;const dt=Yn(de.transcript,$,{authoritative:!0,orderRead:be,peerSource:R()}),cn=Js($.entries,E),js=new Set(de.labelPending);for(const Ju of cn)js.delete(Ju);return{...de,hydrated:de.hydrated||$.entries.length>0||!xr,labelPending:js.size?js:Ht,labelMarked:cv(de.labelMarked,cn),transcript:dt}}),e&&He===void 0&&ze.getState().resolveHeldFromServer(e,$.entries,!$.cursor_missing);const Ft=lt();for(const de of Js($.entries,E))tt.add(de),E.add(de);if(b_($.entries)&&(on=!0),De){const de=w_($.entries,E);for(const dt of de)w.add(dt),E.add(dt);for(const[dt,cn]of y_($.entries,de))fe.set(dt,cn);for(const dt of[...w])tt.has(dt)&&w.delete(dt);w.size>0&&ve--<=0&&w.clear()}et=et||z.size===0||$.entries.some(de=>z.has(rt(de))||Ge.has(de.id)),xt=xt||$.entries.some(de=>Y.has(rt(de)));for(const de of $.entries)Ge.add(de.id);for(const de of $.entries)Be.keys.add(rt(de));nt&&(Be.oldest=nt),Be.hasMore=$.has_more,Be.joined=et,Be.reachedHeld=xt;const an=lt()+w.size;De&<()<Ft&&(C.current.depth=Math.min(wo,Math.max(C.current.depth,It)));let oa=!1;if(De){const de=Tr();oa=__($.entries,de,ie.starts,Ps(),new Set(de.filter(cn=>ie.waiting.has(cn))))||on}if(S_(et&&xt,oa?0:an)||!nt||!$.has_more)return!1;He=nt.id,Z=an>0?mc(an):Ci}return!1},na=()=>{if(we&&cancelAnimationFrame(we),$e&&clearTimeout($e),we=0,$e=0,Xe.current!==T)return;const W=U.current;if(U.current=[],W.length===0)return;const z=new Set,Y=new Map;for(const E of ce.current)A.current.transcript.index.has(E)||ce.current.delete(E);for(const E of x.current)A.current.transcript.index.has(E)||x.current.delete(E);for(const E of A.current.transcript.records)_o(E)&&!ce.current.has(E.id)&&(z.add(E.id),Y.set(E.id,x.current.has(E.id)?E.ts:null));let ee=null;for(const E of W){if(E.type!=="snapshot")continue;const w=E.payload.history,fe=w.entries[0];if(!fe||!w.has_more)continue;const ve=Math.round((fe.ts??0)*1e3);ve>0&&(!ee||ve<ee.ts)&&(ee={id:fe.id,ts:ve})}ov(W);const ie=E=>{const w=E.payload.history.entries,fe=w.at(-1);if(!fe)return!1;if(Lv(E.payload)){if(z.size===0)return!0;const ve=new Set;for(const De of w)ve.add(rt(De));return w.some(De=>z.has(rt(De)))?!0:fm(E.payload.history,Y,ve)}return fe.id===E.payload.frontend.snapshot.history_cursor?!1:z.has(rt(fe))},q=E=>E!=null&&V.current.has(E);let Be=!1;const Me=W.some(E=>E.type==="attention"?!q(E.payload.anchor_id):E.type==="snapshot"&&!ie(E)),Ie=A.current.cold&&!A.current.hydrated&&W.some(E=>E.type==="snapshot"||E.type==="frontend.replace"||E.type==="frontend.update"?E.payload.cold===!1:!1),Ce=new Set(A.current.transcript.argsByCall.keys()),Ge=[],He=new Set;for(const E of W){if(E.type!=="snapshot")continue;const w=se(E,A.current.transcript);w||Fr(x.current,E.payload.history.entries);for(const fe of E.payload.history.entries){w||He.add(rt(fe));const ve=fe.payload?.tool_calls;if(Array.isArray(ve))for(const De of ve)De&&typeof De.id=="string"&&Ce.add(De.id)}for(const fe of E.payload.frontend.snapshot.live_events??[]){const ve=fe.message;!w&&typeof ve?.id=="string"&&He.add(ve.id)}Ge.push(...E.payload.frontend.snapshot.live_events??[])}const It=W.some(E=>E.type==="event"&&Tc.has(String(E.payload.type??""))),We=hc(C.current.attempts,pc(Ge,Ce),Ce,Cc),et=It?hc(C.current.attempts,[...C.current.attempts.keys(),...C.current.settled],Ce,Cc):[],xt=[];for(const E of W){if(E.type!=="event")continue;const w=E.payload;String(w.type??"")==="tool_execution_end"&&String(w.tool_call_id??"")&&xt.push(w)}const on=[];for(const E of xt){const w=String(E.tool_call_id??"");Ce.has(w)||C.current.settled.has(w)||on.push(w)}for(const E of on)C.current.settled.add(E);for(;C.current.settled.size>xc;){const E=C.current.settled.values().next().value;if(E===void 0)break;C.current.settled.delete(E)}for(const[E,w]of fc(xt))C.current.starts.set(E,w);for(;C.current.starts.size>Pc;){const E=C.current.starts.keys().next().value;if(E===void 0)break;C.current.starts.delete(E)}const xr=C.current.settleRows<_v?on:[],tt=[...new Set([...We,...et,...xr])],lt=tt.filter(E=>!C.current.painted.has(E));if(Ge.length>0){C.current.order=pc(Ge,new Set);for(const[E,w]of fc(Ge))C.current.starts.set(E,w);for(;C.current.starts.size>Pc;){const E=C.current.starts.keys().next().value;if(E===void 0)break;C.current.starts.delete(E)}for(const E of m_(Ge))C.current.waiting.add(E);for(const E of k_(Ge))C.current.waiting.delete(E);for(;C.current.waiting.size>kv;){const E=C.current.waiting.values().next().value;if(E===void 0)break;C.current.waiting.delete(E)}}for(const E of[...C.current.attempts.keys()])Ce.has(E)&&C.current.attempts.delete(E);for(Te([...We,...et]);C.current.attempts.size>xc;){const E=C.current.attempts.keys().next().value;if(E===void 0)break;C.current.attempts.delete(E)}if(performance.mark("lop:transcript:flush:start"),O(E=>{let w={...E},fe=w.frontend!==null;Be=!1;let ve=null;const De=Date.now();for(const Z of W){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){w={...w,frontend:null,heldFrontend:w.frontend??w.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:gc(w.transcript)},fe=!1;continue}const jn=je.current;if((Z.type==="open"||"seq"in Z)&&(je.current={epoch:Z.epoch,seq:Z.seq},w={...w,receipt:je.current}),Z.type==="open"){if(w={...w,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const $=w.frontend??w.heldFrontend;w={...w,frontend:null,heldFrontend:$,history:null,transcript:gc(w.transcript)},$&&w.status==="live"&&(w={...w,status:"reconnecting"}),fe=!1}continue}if(!fe){if(Z.type==="event"&&(ve=Ti(ve??w.transcript,Z.payload,De,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const $=K.get(Z),be=se(Z,w.transcript);be&&(Be=!0);const le=Z.payload,nt=!le.history.cursor_missing&&!be;let Ft=ve??w.transcript;nt&&(performance.mark("lop:open:history:start"),Ft=Yn(Ft,le.history,{authoritative:!0,orderRead:$,peerSource:R()}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),ii(ce.current,le.history.entries),Fr(x.current,le.history.entries)),e&&ze.getState().resolveHeldFromServer(e,le.history.entries,nt),performance.mark("lop:open:seed:start"),Ft=h_(Ft,le.frontend.snapshot,De,{epoch:Z.epoch,seq:Z.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const an=Ec(w.frontend??w.heldFrontend,le.frontend.snapshot,le.cold===!0||le.attaching===!0);w={...w,contextCarried:Object.keys(an).length>0,subagentPulses:sv(le.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...le.frontend.snapshot,...an,attention:mn(w.frontend?.attention,le.frontend.snapshot.attention,e)},history:be?w.history:le.history,cold:le.cold,ownerEpoch:le.frontend.epoch,failure:null,hydrated:w.hydrated||nt&&le.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Ft},fe=!0,ve=null}continue}if(Z.type==="attention"){w.frontend&&(w={...w,frontend:{...w.frontend,attention:mn(w.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const $=Z.payload,be=$.changes??{};if(($.degraded===!0||$.paused===!0)&&(w={...w,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!w.frontend)continue;const le=$.epoch!==w.ownerEpoch&&be.epoch===$.epoch,nt=$.changes!==void 0&&be.epoch===$.epoch;(le||$.epoch===w.ownerEpoch&&(w.frontend.sequence<$.sequence||w.frontend.sequence===$.sequence&&nt))&&(w={...w,contextCarried:!1,ownerEpoch:le?$.epoch:w.ownerEpoch,frontend:{...w.frontend,...be,...be.jobs==null&&$.job_deltas?{jobs:cm(w.frontend.jobs??[],$.job_deltas)}:{},attention:mn(w.frontend.attention,be.attention,e),sequence:$.sequence},...typeof $.cold=="boolean"?{cold:$.cold}:{}},nt&&w.liveUpdatesNotice==="update"&&w.liveUpdatesPaused&&(w={...w,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(w.frontend&&Hh(jn,e,Z)){const $=Z.payload.frontend,be=Ec(w.frontend,$.snapshot,Z.payload.cold===!0);w={...w,contextCarried:Object.keys(be).length>0,frontend:{...$.snapshot,...be,attention:mn(w.frontend.attention,$.snapshot.attention,e)},ownerEpoch:$.epoch,cold:Z.payload.cold,...w.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const $=String(Z.payload.type??"");if(Z.payload.action==="reload"){w={...w,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}lv.has($)&&(w={...w,terminal:$}),Tc.has($)&&(w={...w,turnsCompleted:w.turnsCompleted+1});const be=Ti(w.transcript,Z.payload,De,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?ze.getState().stoppedTurns[e]??null:null,queuedAskEngine:Td(w.frontend)});be!==w.transcript&&(w={...w,transcript:be});const le=iv(w.subagentPulses,Z.payload);le!==w.subagentPulses&&(w={...w,subagentPulses:le})}}if(!fe&&ve){for(const Z of ve.index.keys())w.transcript.index.has(Z)||ce.current.add(Z);w={...w,transcript:ve}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),V.current=w.transcript.index,!av(W))return E;if(lt.length>0){const Z=new Set(w.labelPending);for(const jn of lt)Z.add(jn);w={...w,labelPending:Z}}return w.frontend!==null&&w.frontend!==w.heldFrontend&&(w={...w,heldFrontend:w.frontend}),w}),lt.length>0){for(const E of lt)C.current.painted.add(E);for(;C.current.painted.size>Sv;){const E=C.current.painted.values().next().value;if(E===void 0)break;C.current.painted.delete(E)}}const Tr=Me||Be,Ps=xr.length>0&&We.length===0&&et.length===0&&!Tr&&!Ie;if(Tr||tt.length>0||Ie){const E=new Set(tt),w=C.current.order;Ir(T,He,tt.length>0?{targets:E,order:w,starts:C.current.starts,waiting:C.current.waiting,every:new Set([...w,...E]),found:new Set(Js(W.flatMap(fe=>fe.type==="snapshot"?fe.payload.history.entries:[]),new Set(w))),pending:lt}:Oc,1,Ps?fe=>{C.current.settleRows+=fe}:void 0,z,ee)}},On=()=>{const W=pe;if(pe=null,f.current=null,p.current+=1,h.current&&(window.clearTimeout(h.current),h.current=0),g.current+=1,!!W){H=!0;try{W()}finally{H=!1}}},Pn=()=>{const W=wi(A.current.transcript);Se(),he=window.setTimeout(()=>{he=0,Xe.current===T&&(On(),O(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:za(Zn.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ee&&(Ee=!0,oe=window.setTimeout(()=>{oe=0,Xe.current===T&&sa()},pv)))},fv);const z=_();pe=am({sessionId:e,epoch:xn.current.epoch,afterSeq:xn.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(A.current.transcript).slice(0,512),...z?{peerJournalSource:!0}:{}}:{}},Y=>{if(Xe.current===T){if(Y.kind==="error"||Y.kind==="end"){if(H)return;if(Se(),On(),Y.kind==="error"&&Y.status===404){if(!n){e&&ze.getState().retireDraftWarm(e),O(q=>({...q,subscriptionId:null}));return}e&&(z_(e),Q_(e),ev(e),ze.getState().retireDraftsForSession(e)),O(q=>({...q,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...q.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ee=Y.kind==="error"?Y.detail??"The event stream failed.":"The event stream closed unexpectedly.";if(O(q=>({...q,subscriptionId:null})),ue>=uv){O(q=>({...q,status:"unavailable",failure:za(ee),...q.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}ue+=1;const ie=je.current;ie&&(xn.current={epoch:ie.epoch,afterSeq:ie.seq}),O(q=>q.status==="unavailable"&&ue>1?q:{...q,status:"reconnecting",failure:null}),me=window.setTimeout(()=>{me=0,Xe.current===T&&Pn()},Ic(ue));return}if(Y.data!==void 0)try{const ee=Y.data,ie=ee.length>=yv;ie&&performance.mark("lop:open:parse:start");const q=JSON.parse(ee);q.type==="snapshot"&&K.set(q,W),ie&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),q.type==="snapshot"&&(ue=0,Se(),Ee=!1),U.current.push(q),we||(we=requestAnimationFrame(na)),$e||($e=window.setTimeout(na,gv))}catch{}}}),f.current={sessionId:e,peer:z},p.current+=1},ra=()=>{me!==0&&(window.clearTimeout(me),me=0),xn.current={},je.current=null,On(),Pn()},sa=()=>{ue=0,oe&&(window.clearTimeout(oe),oe=0),me&&(window.clearTimeout(me),me=0),D&&(window.clearTimeout(D),D=0),O(W=>({...W,failure:null,status:W.status==="unavailable"?"connecting":W.status,transcript:$r(W.transcript,!1)})),A.current.hydrated||Ir(T,new Set(A.current.transcript.index.keys())),!pe&&Pn()};Pn(),Is.current=sa,xs.current=()=>{A.current.liveUpdatesReloading||(O(W=>({...W,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),ue=0,me&&(window.clearTimeout(me),me=0),oe&&(window.clearTimeout(oe),oe=0),ra())},Ts.current=()=>{!A.current.hydrated&&Tn.current===0&&Ir(T,new Set(A.current.transcript.index.keys()))};const Yu=Ev(e,ra),ia=()=>{if(!t||!e||m.current===e)return;const W=f.current;W===null||W.sessionId!==e||W.peer||_()&&(m.current=e,On(),Pn())};y.current=ia;const Qu=ze.subscribe(()=>{ia()});return()=>{Xe.current+=1,Is.current=null,Ts.current=null,xs.current=null,y.current=null,Qu(),h.current&&(window.clearTimeout(h.current),h.current=0),Yu(),On(),we&&cancelAnimationFrame(we),$e&&clearTimeout($e),me&&clearTimeout(me),D&&clearTimeout(D),qe.current&&(window.clearTimeout(qe.current),qe.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),oe&&window.clearTimeout(oe),Se(),U.current=[]}},[O,e,t,n,a,_,b,R]),v.useEffect(()=>{!e||!t||y.current?.()},[e,t,d]),v.useEffect(()=>{xn.current={},je.current=null,V.current=st.index;const T=Mv(S.current,e,n);S.current=e;const K=e?Fd(e):null;V.current=T?A.current.transcript.index:(K?.transcript??st).index;const se=new Set(T?ce.current:[]);for(const H of K?.replayBorn??[])se.add(H);const pe=T?A.current.transcript.index:(K?.transcript??st).index;for(const H of se)pe.has(H)||se.delete(H);ce.current=se,T||(x.current=new Set),O(H=>({...H,frontend:null,heldFrontend:T?H.heldFrontend:null,contextCarried:T?H.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:T?H.turnsCompleted:0,transcript:T?H.transcript:K?.transcript??st,stale:T?H.stale:K!==null,missing:T?H.missing:!1,status:"connecting",subagentPulses:{},labelPending:K?.owedLabels??Ht,labelMarked:K?.markLabels??Hn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),C.current=jc(e)},[e,n]),v.useEffect(()=>{if(e)return()=>{const T=A.current.transcript;T.records.length>0&&W_(e,{transcript:T,owedLabels:new Set([...A.current.labelPending].filter(K=>si(C.current,A.current.transcript.argsByCall,K,ri(A.current)))),markLabels:new Set(A.current.labelMarked),replayBorn:new Set(ce.current)});for(const K of re.current)C.current.inFlight.delete(K);re.current.clear()}},[e]);const qe=v.useRef(0);v.useEffect(()=>{if(M.labelPending.size===0&&M.labelMarked.size===0){qe.current&&(window.clearTimeout(qe.current),qe.current=0);return}if(qe.current)return;const T=()=>{qe.current=0;const K=A.current.labelPending,se=A.current.labelMarked;if(K.size===0&&se.size===0)return;const pe=C.current;for(const H of K)if(pe.inFlight.has(H)){qe.current=window.setTimeout(T,ni);return}for(const H of se)if(pe.inFlight.has(H)){qe.current=window.setTimeout(T,ni);return}O(H=>H.labelPending.size===0&&H.labelMarked.size===0?H:{...H,labelPending:Ht,labelMarked:Hn})};qe.current=window.setTimeout(T,ni)},[O,M.labelPending,M.labelMarked]);const yt=v.useRef(0);v.useEffect(()=>{if(M.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),O(T=>T.labelHoldLate?{...T,labelHoldLate:!1}:T);return}M.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,O(T=>T.labelPending.size===0||T.labelHoldLate?T:{...T,labelHoldLate:!0})},bv))},[O,M.labelPending,M.labelHoldLate]);const Et=v.useRef(e);Et.current=e;const Cn=v.useRef({id:e,epoch:0});Cn.current.id!==e&&(Cn.current={id:e,epoch:Cn.current.epoch+1});const Cs=v.useRef(null);Cs.current===null&&(Cs.current=tv());const As=v.useRef(!1),An=v.useRef(null),[Zo,zu]=v.useState(0);v.useEffect(()=>{const T=M.transcript,K=ut(T);if(!e||!a||!T.orderNeedsReconcile&&(!T.journalGeneration||K.length===0)||As.current)return;const se=D=>({fields:JSON.stringify([Zo,e,D.viewEpoch,Ye(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),pe=se(T);if(An.current?.fields===pe.fields&&An.current.demand===pe.demand)return;An.current=pe;const H=e,we=T.viewEpoch;As.current=!0;let $e=null,ue=T;const me=D=>{if(!D.peer||Et.current!==H||A.current.transcript.viewEpoch!==we||p.current!==D.streamEpoch)return;const he=D.kind==="authority"?D.frame.payload.history:D.page,oe=he.journal_order_state;if(oe==="ready"){h.current&&(window.clearTimeout(h.current),h.current=0),O(Se=>{const Te=$r(Se.transcript,!1);return Te===Se.transcript?Se:{...Se,transcript:Te}});return}if(oe==="unavailable"){if(h.current&&(window.clearTimeout(h.current),h.current=0),he.reconcile===!0)return;O(Se=>{const Te=$r(Se.transcript,!0);return Te===Se.transcript?Se:{...Se,transcript:Te}});return}if(oe!=="building")return;h.current&&(window.clearTimeout(h.current),h.current=0);const Ee=++g.current;h.current=window.setTimeout(()=>{h.current=0,g.current===Ee&&Et.current===H&&A.current.transcript.viewEpoch===we&&p.current===D.streamEpoch&&O(Se=>{const Te=$r(Se.transcript,!0);return Te===Se.transcript?Se:{...Se,transcript:Te}})},hv)};dm({getTranscript:()=>A.current.transcript,isCurrent:()=>Et.current===H&&A.current.transcript.viewEpoch===we,sweep:(D,he)=>{if(!b())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${H}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const oe=D.journalGeneration;if(typeof oe!="string"||oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${H}/history`,query:new URLSearchParams};if(Nl(D,he?.("lookup")).length>0){const Te=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:oe});return{kind:"lookup",path:`/v1/desktop/sessions/${H}/history`,query:Te}}if(io(D).length>0){const Te=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:oe});return{kind:"payload",path:`/v1/desktop/sessions/${H}/history`,query:Te}}return{kind:"none",path:`/v1/desktop/sessions/${H}/history`,query:new URLSearchParams}},read:async(D,he)=>{ue=A.current.transcript,An.current=se(ue);const oe=b(),Ee=p.current;if(he==="lookup"||he==="payload"){const Te=A.current.transcript.journalGeneration,sn=await xe({op:"sessions.history",sessionId:H,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:he==="payload"?"payload":"metadata",...typeof Te=="string"&&Te.length>0?{expectedJournalGeneration:Te}:{}});return he==="payload"?{kind:"payload",page:sn,peer:oe,streamEpoch:Ee}:{kind:"lookup",page:sn,peer:oe,streamEpoch:Ee}}return{kind:"authority",frame:await xe({op:"sessions.get",sessionId:H,journalOrder:!0,orderIds:D,...oe?{peerJournalSource:!0}:{}}),peer:oe,streamEpoch:Ee}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${H}`,commit:(D,he,oe)=>{D.peer&&p.current!==D.streamEpoch||(O(Ee=>Et.current!==H||Ye(Ee.transcript)!==he||Ee.transcript.viewEpoch!==we?Ee:{...Ee,transcript:D.kind==="authority"?D.peer?uc(Ee.transcript,D.frame.payload.history,{authoritative:!0,orderRead:oe}):a_(Ee.transcript,D.frame.payload.history,oe):D.kind==="payload"?c_(Ee.transcript,D.page,oe,he):uc(Ee.transcript,D.page,{authoritative:!1})}),me(D))}}).then(D=>{$e=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{As.current=!1;const D=A.current.transcript,he=$e??ue;$e&&Et.current===H&&D.viewEpoch===we&&!D.orderNeedsReconcile&&(An.current=se(he)),(Et.current!==H||D.viewEpoch!==we||Ye(D)!==Ye(he)||D.orderWantedGeneration!==he.orderWantedGeneration||D.orderNeedsReconcile!==he.orderNeedsReconcile||D.orderDemand!==he.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(he)))&&zu(oe=>oe+1)})},[O,e,a,b,M.transcript,Zo]);const Er=v.useCallback(async()=>{const T=Cs.current;if(!e||!T)return{kind:"nothing-to-load"};const K=e,se=Cn.current.epoch,pe=()=>Cn.current.epoch===se,H=A.current.transcript.viewEpoch,we=()=>A.current.transcript.viewEpoch===H,$e=await T.load(`${K}#${se}`,{getTranscript:()=>A.current.transcript,readPage:ue=>xe({op:"sessions.history",sessionId:K,beforeId:ue,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>pe()&&we(),commit:ue=>O(me=>{const D=ue(me.transcript);return D===me.transcript?me:{...me,transcript:D}}).transcript,setLoading:ue=>{pe()&&O(me=>me.loadingOlder===ue?me:{...me,loadingOlder:ue})},peerSource:R});return pe()&&($e.kind==="failed"?O(ue=>ue.olderFailed?ue:{...ue,olderFailed:!0}):$e.kind==="applied"&&O(ue=>ue.olderFailed?{...ue,olderFailed:!1}:ue)),$e},[O,e,b,R]),Vo=v.useCallback(async()=>(await Er()).kind==="applied",[Er]),Os=v.useRef(!1),Ko=v.useCallback(async(T,K)=>{if(!e||Os.current)return!1;const se=e;Os.current=!0;const pe=Ye(A.current.transcript);try{const H=await xe({op:"sessions.history",sessionId:se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}});return Et.current!==se||Ye(A.current.transcript)!==pe||A.current.transcript.viewEpoch!==K?!1:(O(we=>Ye(we.transcript)!==pe?we:{...we,transcript:Yn(we.transcript,H,{keepPaging:!0,peerSource:R()})}),ii(ce.current,H.entries),Fr(x.current,H.entries),O_(H.entries,T))}catch{return!1}finally{Os.current=!1}},[O,e,b,R]);v.useEffect(()=>r?Pv(r,K=>{O(se=>{const pe=K(se.transcript);return pe===se.transcript?se:{...se,transcript:pe}})}):void 0,[O,r]),v.useEffect(()=>{r&&Ov(r,M.transcript)},[r,M.transcript]);const Yo=v.useCallback(()=>{O(T=>({...T,transcript:E_(T.transcript),olderFailed:!1,heldFrontend:null}))},[O]),Qo=v.useCallback(()=>{Is.current?.()},[]),Jo=v.useCallback(()=>{xs.current?.()},[]),Xo=v.useCallback(()=>{Ts.current?.()},[]),qo=v.useCallback((T,K="info")=>{O(se=>({...se,transcript:T_(se.transcript,T,K)}))},[O]),ea=v.useCallback(T=>{O(K=>({...K,pendingModel:T}))},[O]),ta=v.useCallback(()=>{O(T=>T.pendingModel===null?T:{...T,pendingModel:null})},[O]);return v.useEffect(()=>{const T=M.pendingModel;if(!T)return;const K=Xs(T);if(!K)return;const se=M.frontend;(Xs(se?.selected_model)===K||Xs(se?.effective_model)===K)&&O(pe=>({...pe,pendingModel:null}))},[O,M.frontend,M.pendingModel]),v.useEffect(()=>{if(!M.pendingModel)return;const T=window.setTimeout(()=>O(K=>({...K,pendingModel:null})),dv);return()=>window.clearTimeout(T)},[O,M.pendingModel]),v.useMemo(()=>({...M,awaitingHydration:t&&!!e&&n&&!M.hydrated,loadOlder:Vo,loadOlderDetailed:Er,refreshTail:Ko,clearView:Yo,addNote:qo,paintPendingModel:ea,clearPendingModel:ta,retry:Qo,rehydrate:Xo,reloadFromHistory:Jo}),[M,t,e,n,Vo,Er,Ko,Yo,qo,ea,ta,Qo,Xo,Jo])}function ys(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
34
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!cc.test(c)&&!qy(c),r=t.find(n),s=t.find(c=>cc.test(c)&&!c.startsWith("</"));let i=r??s??e.trim();const a=t.indexOf(i);if(a>=0&&i.endsWith(":")){const c=t.slice(a+1).find(n);c&&(i=`${i} ${c}`)}return Id(i)}function qy(e){return By.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Id(e){const t=e.trim();if(t.length<=Kn)return t;const n=t.slice(0,Kn),r=n.lastIndexOf(" ");return`${(r>0?n.slice(0,r):n).trimEnd()}…`}const e_="harness_injected",xd=e=>!e||typeof e!="object"?!1:e[e_]===!0;function Td(e){return e!=null&&(Array.isArray(e.asks)||e.asks_open!=null)}function Cd(e){if(!e||typeof e!="object")return!1;const t=e.ask_gate;return!t||typeof t!="object"?!1:!!t.hidden}const t_="ask";function lc(e,t){return t===!0&&String(e??"")===t_}function Ad(e,t){const n=e.payload??{},r=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const a=t?.kind==="compaction"?t.text:bd,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:r,text:a,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const a=n.details??{},c=vd(String(a.detail??""));return{kind:"notice",id:e.id,ts:r,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const a=n.details??{};if(typeof a.anchor=="string"){if(a.kind==="closed")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:Sd,level:"info"};if(a.kind==="retired")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:kd,level:"warning"};if(a.kind==="error"||a.kind==="interrupted")return{kind:"notice",id:a.anchor,ts:r,complete:!0,text:a.kind==="error"?"Stopped with an error":"Interrupted",level:a.kind==="error"?"error":"warning"}}}if(e.type==="custom"&&n.custom_type===Ei){const a=n.details??{};return sc(r,a,t)}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const a=String(n.custom_type??"");if(Ay.has(a))return null;const c=n.details??{};if(a==="hub_message"){const u=Si(c);if(!u.body.trim())return null;const f=t?.kind==="custom"?t.receipt:void 0;return f&&Zs(f.sender,u.sender)&&(u.sender=f.sender),{kind:"custom",id:e.id,ts:r,customType:a,text:u.envelope,attribution:"user",...Wr(a,u.envelope||u.body,c),receipt:f&&Object.keys(u).every(p=>f[p]===u[p])?f:u,images:Zt(n.content?n:c,e.id,t?.kind==="custom"?t.images:void 0)}}if(a===My){const{body:u,sender:f}=Vl(c);return{kind:"peer",id:e.id,ts:r,body:u,sender:t?.kind==="peer"&&Zs(t.sender,f)?t.sender:f}}if(a===Ly){if(qm(c)||eg(c))return null;const u=String(c.text??"");return u.trim()?{kind:"wake",id:e.id,ts:r,text:u}:null}if(a===Dy){const u=c.answers,f={};if(u&&typeof u=="object")for(const[g,m]of Object.entries(u))f[String(g)]=Array.isArray(m)?m.map(y=>String(y)):[];const p=c.questions,h=Array.isArray(p)?p.flatMap(g=>{if(!g||typeof g!="object")return[];const m=g;return[{id:String(m.id??""),question:String(m.question??""),secret:m.secret===!0}]}):[];return{kind:"ask_response",id:e.id,ts:r,askId:String(c.ask_id??""),status:String(c.status??"answered"),by:c.by&&typeof c.by=="object"?c.by:null,reason:typeof c.reason=="string"?c.reason:null,questions:h,answers:f,secretLost:c.secret_lost===!0}}if(a===Ny){const u=Number(c.waited_s);return{kind:"ask_timeout",id:e.id,ts:r,askId:String(c.ask_id??""),waitedS:Number.isFinite(u)&&u>0?u:0,urgent:c.urgent===!0}}if(a===Ei)return sc(r,c,t);const d=(a==="audio_settle_v1"&&c.terminal===!0?Bg(c):null)??String(c.text??c.detail??"");return d.trim()?{kind:"custom",id:e.id,ts:r,customType:a,text:d,attribution:n.attribution??"system",...Wr(a,d,c)}:null}const i=String(n.role??"");if(i==="user"){const a=Ed(n.provider_payload);if(a){const u=Si({...a,text:ft(n)});if(u.body.trim()){const f=t?.kind==="custom"?t.receipt:void 0;f&&Zs(f.sender,u.sender)&&(u.sender=f.sender);const p=t?.kind==="custom"||t?.kind==="user"?t.images:void 0;return{kind:"custom",id:e.id,ts:r,customType:"hub_message",text:u.envelope,attribution:"user",...Wr("hub_message",u.envelope||u.body,{...a,text:ft(n)}),receipt:f&&Object.keys(u).every(h=>f[h]===u[h])?f:u,images:Zt(n,e.id,p)}}}if(xd(n.provider_payload))return null;const c=ft(n);if(rd(c))return null;if(c.startsWith("Harness recovery notice:"))return{kind:"notice",id:e.id,ts:r,text:c,level:"warning"};const l=ms(c),d=Sy(n,e.id,t?.kind==="user"?t.documents:void 0);return{kind:"user",id:e.id,ts:r,text:c,images:Zt(n,e.id,t?.kind==="user"?t.images:void 0),...d.length?{documents:d}:{},...l?{skill:l}:{}}}if(i==="assistant"){const a=Array.isArray(n.tool_calls)?n.tool_calls:[],c=ft(n);return!c&&a.length>0?{kind:"assistant",id:e.id,ts:r,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),callsTools:!0,error:!1}:{kind:"assistant",id:e.id,ts:r,text:c,complete:!0,streaming:!1,callsTools:a.length>0,stopReason:n.stop_reason??null,error:!!n.is_error}}if(i==="tool"){const a=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{};if(Cd(l))return null;const d=hd(l.__fault);return{kind:"tool",id:`tool:${a}`,ts:r,toolCallId:a,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:ft(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:Zt(n,`tool:${a}`,t?.kind==="tool"?t.images:void 0),...nd(c.details,t?.kind==="tool"?t:null),diff:td(ed(c.details),t?.kind==="tool"?t.diff:null),stopped:d,delivery:Kl(c.details,t?.kind==="tool"?t.delivery:null),details:ki(c.details,t?.kind==="tool"?t.details??null:null)}}return null}function n_(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}const r_=/^(?:tool|compaction|local):/;function s_(e){for(const t of e.records){switch(t.kind){case"user":case"assistant":case"custom":case"peer":case"wake":case"compaction":case"ask_response":case"ask_timeout":break;default:continue}if(!(t.kind==="user"&&t.local)&&!r_.test(t.id))return t.id}return null}function i_(e,t){const n=Wg(t);if(n)return e.records[e.index.get(n)??-1]}function go(e){const t=Dl(e,e.records);if(t===e.records)return e;const n=t.map(sd);return{...e,records:n,index:Ke(n)}}const fr=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Od(e,t,n,r){const s={...e,sourceEntryId:t,journalSeq:r,journalGeneration:n};if(e.kind==="user"&&(e.provisional===!0||e.local===!0)){const{provisional:i,local:a,...c}=s;return c}return s}function o_(e){const t=new Set,n=new Set;for(const r of e.records){const s=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof s!="string"||s.length<1||s.length>128||(t.add(s),r.journalGeneration===e.journalGeneration&&fr(r.journalSeq)&&n.add(s))}return{carried:t,admitted:n}}function yo(e){if(e.journalSeq===void 0&&e.journalGeneration===void 0)return e;const{journalSeq:t,journalGeneration:n,...r}=e;return r}function dc(e,t){const n=new Set;for(const a of t)typeof a=="string"&&a.length>0&&a.length<=128&&n.add(a);if(n.size===0)return e;let r=!1;const s=e.records.map(a=>{const c=a.sourceEntryId??(a.kind==="tool"||a.kind==="supplement"?null:a.id);if(c===null||!n.has(c))return a;const l=yo(a);return l!==a&&(r=!0),l});let i=r?{...e,records:s}:e;return i=Pd(i,n),i}function Pd(e,t){if(e.journalPeerSource!==!0)return e;const{carried:n,admitted:r}=o_(e),s=e.orderRevision??0,i=e.journalBodyOwed;let a=null;const c=e.journalSourceVoid;let l=null;for(const d of t)typeof d!="string"||d.length<1||d.length>128||!n.has(d)||r.has(d)||(a||(a=new Map(i??[])),a.set(d,s),c?.has(d)&&(l||(l=new Set(c)),l.delete(d)));return a?{...e,journalBodyOwed:a,...l?{journalSourceVoid:l}:{}}:e}function is(e,t,n){const r=n&&e.journalSourceUnavailable===!0?{...e,journalSourceUnavailable:void 0}:e;if(t.length===0)return r;const s=r.journalBodyOwed;let i=null;const a=r.journalSourceVoid;let c=null;for(const l of t)s?.has(l)&&(i||(i=new Map(s)),i.delete(l)),a?.has(l)&&(c||(c=new Set(a)),c.delete(l));return!i&&!c?r:{...r,...i?{journalBodyOwed:i}:{},...c?{journalSourceVoid:c}:{}}}function br(e,t){return e.journalPeerSource===!0===t?e:{...e,journalPeerSource:t}}function jd(e,t){return t.journal_order_state!=="ready"||e.journalSourceUnavailable!==!0?e:{...e,journalSourceUnavailable:void 0}}function a_(e,t,n){let r=Rn(e,t,t.entries.map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),!0,n);for(const i of t.entries)r=so(r,{...i.payload,id:i.id});const s=br(r,!1);return go(s.journalPeerSource===void 0&&!s.journalBodyOwed&&!s.journalSourceVoid&&s.journalSourceUnavailable===void 0?s:{...s,journalBodyOwed:void 0,journalSourceVoid:void 0,journalSourceUnavailable:void 0})}function uc(e,t,n){let r=Rn(e,t,(t.entries??[]).map(i=>({id:i.id,journal_seq:i.journal_seq,role:i.payload?.role,tool_call_id:i.payload?.tool_call_id})),n.authoritative,n.orderRead,{peer:!0});if(r=br(r,!0),t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===r.journalGeneration){const i=[...Object.keys(t.journal_ordinals??{}),...(t.entries??[]).map(c=>c.id)];i.length>0&&(r=Pd(r,i));const a=(t.journal_missing_ids??[]).filter(c=>typeof c=="string"&&c.length>0&&c.length<=128);if(a.length>0){r=is(r,a,!1);const c=new Set(r.journalSourceVoid??[]);for(const l of a)c.add(l);r={...r,journalSourceVoid:c}}}return r=jd(r,t),go(r)}function c_(e,t,n,r){let s=Rn(e,t,[],!1,n,{peer:!0});s=br(s,!0);const i=s.journalBodyOwed,a=h=>r!==void 0&&(i?.get(h)??Number.NEGATIVE_INFINITY)>r,c=t.journal_order_state==="ready"&&typeof t.journal_generation=="string"&&t.journal_generation===s.journalGeneration,l=c?[...t.entries??[],...t.dependency_entries??[]]:[],d=[];let u=s.records,f=s.index;if(l.length>0){const h=new Map;for(const g of l){if(typeof g.id!="string"||g.id===""||a(g.id))continue;const m=`tool:${String(g.payload?.tool_call_id??"")}`,y=f.get(g.id)??f.get(m),_=y===void 0?void 0:u[y];if(!_)continue;let b=Ad(g,_);b&&(b={...b,sourceEntryId:g.id},fr(g.journal_seq)?(b=Od(b,g.id,t.journal_generation,g.journal_seq),d.push(g.id)):b=yo(b),h.set(_.id,b))}h.size>0&&(u=u.map(g=>h.get(g.id)??g),f=Ke(u))}let p=u===s.records?s:{...s,records:u,index:f};if(c){p=is(p,d,!1);const h=(t.source_missing_ids??[]).filter(g=>typeof g=="string"&&g.length>0&&g.length<=128&&!a(g));if(h.length>0){p=is(p,h,!1);const g=new Set(p.journalSourceVoid??[]);for(const m of h)g.add(m);p={...p,journalSourceVoid:g}}}return p=jd(p,t),go(p)}function $r(e,t=!0){return e.journalSourceUnavailable===!0===t?e:{...e,journalSourceUnavailable:t}}function Yn(e,t,n={}){let r=e;const s=r,i=[],a=x=>br(is(x,i,n.peerSource===!0&&t.journal_order_state==="ready"),n.peerSource===!0);if(r=Rn(r,t,t.entries.map(x=>({id:x.id,journal_seq:x.journal_seq,role:x.payload?.role,tool_call_id:x.payload?.tool_call_id})),n.authoritative===!0,n.orderRead,{peer:n.peerSource===!0}),t.journal_generation&&t.journal_generation!==r.journalGeneration)return a(r);const c=n.peerSource===!0&&typeof t.journal_generation=="string"&&t.journal_generation.length>0&&t.journal_generation===r.journalGeneration;for(const x of t.entries)r=so(r,{...x.payload,id:x.id});const l=n.keepPaging===!0&&r.viewEpoch>0,d=[];for(const x of t.entries){if(l&&!I_(x,r.clearedAt))continue;const C=r.records[r.index.get(x.id)??-1]??r.records[r.index.get(`tool:${String(x.payload?.tool_call_id??"")}`)??-1]??i_(r,x);let re=Ad(x,C);re&&r.journalMode&&(re={...re,sourceEntryId:x.id}),re&&c&&fr(x.journal_seq)?(re=Od(re,x.id,t.journal_generation,x.journal_seq),i.push(x.id)):re&&n.peerSource===!0&&(re=yo(re)),re&&d.push(re)}let u=r.argsByCall,f=!1;for(const x of t.entries){const C=x.payload?.tool_calls;if(!Array.isArray(C))continue;const re=Math.round((x.ts??0)*1e3);for(const je of C)!je||typeof je.id!="string"||u.has(je.id)||(f||(u=new Map(u),f=!0),u.set(je.id,{...je,anchoredAt:re,anchorId:x.id}))}for(let x=0;x<d.length;x++){const C=d[x];if(C.kind!=="tool")continue;const re=u.get(C.toolCallId);if(!re)continue;const je=re.arguments??null;d[x]={...C,args:je,intent:typeof je?.i=="string"?je.i:null}}const p=f?r.records.map(x=>{if(x.kind!=="tool"||x.args)return x;const re=u.get(x.toolCallId)?.arguments??null;return re?{...x,args:re,intent:x.intent??(typeof re.i=="string"?re.i:null)}:x}):r.records,h=new Set(t.entries.map(x=>x.id)),g=n.peerSource===!0&&n.replace===!0?r.records.filter(x=>x.kind==="user"&&(x.provisional===!0||x.local===!0)&&!h.has(x.id)):[],m=n.replace?g.length>0?{...st,records:g,index:Ke(g)}:st:{...r,records:p},y=new Map(m.records.map(x=>[x.id,x]));let _=r!==s||n.replace||!n.replace&&p!==r.records;for(const x of d){const C=y.get(x.id);if(!C){_=!0,y.set(x.id,x);continue}if(C.kind==="tool"&&x.kind==="tool"){const re={...x,args:x.args??C.args,intent:x.intent??C.intent,images:yd(x.images,C.images,"current")};xi(C,re)||(_=!0,y.set(x.id,re));continue}xi(C,x)||(_=!0,y.set(x.id,x))}const b=r.compacting&&t.entries.some(x=>r.index.has(x.id)||Math.round((x.ts??0)*1e3)<r.compactingSince?!1:x.type==="compaction"||x.type==="message"&&x.payload?.custom_type==="compaction_refused"),R=t.entries[0],M=R?Math.round((R.ts??0)*1e3):0,G=r.journalMode?kt:Iy(m.records,M,n.statedByOwner!==!1);let A=m.oldestId,O=m.oldestTs,S=r.hasMore;n.keepPaging||(n.replace||r.oldestId===null?(R&&(A=R.id,O=M),S=t.has_more):n.pagedBefore!==void 0?R?(A=R.id,O=M,S=t.has_more):S=!1:R&&(r.journalMode?(r.journalPositions?.get(R.id)?.seq??Number.POSITIVE_INFINITY)<(r.journalPositions?.get(r.oldestId??"")?.seq??-1):M>0&&M<r.oldestTs)&&(A=R.id,O=M,S=t.has_more));const U=A!==r.oldestId||O!==r.oldestTs;if(!_&&!U&&r.hasMore===S&&!b&&G.size===0)return a(r);const V=G.size===0?[...y.values()]:[...y.values()].map(x=>G.has(x.id)?xy(x):x),ce=wd(ur(V,n.statedByOwner===!1?kt:new Set(d.map(x=>x.id)),r));return n.keepPaging?a({...r,records:ce,index:Ke(ce),argsByCall:u}):a({...r,records:ce,index:Ke(ce),oldestId:A,oldestTs:O,hasMore:S,argsByCall:u,compacting:b?!1:r.compacting,compactingSince:b?0:r.compactingSince})}const l_=/^(?:local|notice|retry|subagent|compaction):/;function _o(e){switch(e.kind){case"user":return!e.local&&!e.provisional;case"assistant":return!e.streaming;case"tool":return e.phase==="done";default:return!l_.test(e.id)}}function d_(e,t,n=kt){if(e.journalMode||t.ts<=0)return e;const r=e.records.filter(s=>!(s.ts<t.ts&&_o(s)&&!n.has(s.id)));return r.length===e.records.length?e:{...e,records:r,index:Ke(r),oldestId:t.id,oldestTs:t.ts,hasMore:!0}}const _t={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0,idlessFrameRefused:0};function Qs(e){const t=e?.id;return typeof t=="string"&&t!==""?t:null}function Ti(e,t,n=Date.now(),r={}){let s=e;const i=t.message;if(t.type==="journal_order_ready"){const l=typeof t.journal_generation=="string"?t.journal_generation:void 0;if(s={...s,orderNeedsReconcile:!0,orderWantedGeneration:t.reconcile===!0?void 0:l,orderDemand:t.reconcile===!0?{}:{generation:l}},t.reconcile===!0)return s;const d=Rn(s,{journal_generation:typeof t.journal_generation=="string"?t.journal_generation:void 0},Array.isArray(t.rows)?t.rows:[],!1),u=ur(d.records,kt,d);return d===s&&u===s.records?s:{...d,records:u,index:Ke(u)}}i&&(s=so(s,i));const a=r.frame,c=r.queuedAskEngine;switch(t.type){case"agent_start":{const l=Number(t.generation??s.generation+1);return l===s.generation?s:{...s,generation:l,compacting:!1,compactingSince:0}}case"compaction_start":return s.compacting?s:{...s,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??s.generation)<s.generation)return s;let d=s;for(const u of s.records)if(u.kind==="assistant"&&u.streaming&&(d=ge(d,{...u,streaming:!1,settledAt:n,callsTools:!1,stopReason:t.aborted?"aborted":u.stopReason})),u.kind==="tool"&&u.phase!=="done"){const f=u.phase==="composing"||u.phase==="queued";d=ge(d,{...u,phase:"done",startedAt:null,stopped:!!t.aborted||f,neverSent:u.neverSent||f})}return d}case"message_start":{const l=Qs(i);if(i===void 0||l===null)return _t.idlessFrameRefused+=1,s;const d=s.records[s.index.get(l)??-1];if(i.role==="user"){const u=Ed(i.provider_payload);if(u){const g=ft(i),m=Si({...u,text:g});if(m.body.trim()){const y=d?.kind==="user"&&d.provisional===!0;return ge(s,{kind:"custom",id:l,ts:y?os(s,n):n,customType:"hub_message",text:m.envelope,attribution:"user",...Wr("hub_message",m.envelope||m.body,{...u}),receipt:m,images:Zt(i,l,d?.kind==="custom"||d?.kind==="user"?d.images:void 0)})}}if(xd(i.provider_payload))return s;const f=ft(i);if(rd(f))return s;const p=d?.kind==="user"&&d.provisional===!0,h=ms(f);return ge(s,{kind:"user",id:l,ts:p?os(s,n):n,text:f,images:Zt(i,l,d?.kind==="user"?d.images:void 0),...p?{provisional:!0}:{},...h?{skill:h}:{}})}return i.role!=="assistant"||d?s:ge(s,{kind:"assistant",id:l,ts:n,text:"",streaming:!0,...a?{frame:a}:{},stopReason:null,error:!1})}case"message_update":{const l=Qs(i);if(i===void 0||l===null)return _t.idlessFrameRefused+=1,s;const d=s.index.get(l),u=String(t.delta??""),f=ft(i);if(d===void 0)return!f&&!u?s:ge(s,{kind:"assistant",id:l,ts:n,text:f?f+u:u,streaming:!0,truncated:f===""?"prefix":void 0,...a?{frame:a}:{},stopReason:null,error:!1});const p=s.records[d];if(p.kind!=="assistant")return s;if(!p.streaming)return _t.settledAssistantUpdate+=1,s;if(r.seed!==!0&&a&&p.frame&&a.epoch===p.frame.epoch&&a.seq<=p.frame.seq)return _t.staleUpdateFrameDropped+=1,s;const h=Ey(p.frame,a);if(r.seed===!0&&!f)return!p.text&&!u?s:(_t.seededDeltaWithheld+=p.text?1:0,ge(s,{...p,text:p.text||u,...h?{frame:h}:{},truncated:p.text?"interrupted":"prefix"}));let g;if(f){if(g=f+u,g.length<=p.text.length)return s}else{if(!u)return s;g=p.text+u}return ge(s,{...p,text:g,...h?{frame:h}:{},truncated:f?void 0:p.truncated})}case"message_end":{const l=Qs(i);if(i===void 0)return _t.idlessFrameRefused+=1,s;if(l===null){if(i.role!=="assistant")return _t.idlessFrameRefused+=1,s;let g;for(const _ of s.records)if(!(_.kind!=="assistant"||!_.streaming)){if(g!==void 0)return _t.idlessFrameRefused+=1,s;g=_}if(g===void 0)return _t.idlessFrameRefused+=1,s;const m=Array.isArray(i.tool_calls)?i.tool_calls:[],y={...g,streaming:!1,settledAt:g.settledAt??n,callsTools:m.length>0,...g.text||m.length===0?{complete:!0}:{}};return ge(s,y)}if(i.role!=="assistant")return s;const d=s.index.get(l),u=ft(i),f=d===void 0?void 0:s.records[d],p=Array.isArray(i.tool_calls)?i.tool_calls:[],h={kind:"assistant",id:l,ts:d===void 0?n:s.records[d].ts,text:u,...u||p.length===0?{complete:!0}:{},streaming:!1,callsTools:p.length>0,settledAt:f?.kind==="assistant"&&f.settledAt!==void 0?f.settledAt:n,stopReason:i.stop_reason??null,error:!!i.is_error};return ge(s,h)}case"history_delta":{const d=(Array.isArray(t.messages)?t.messages:[]).filter(R=>String(R.id??"")!==""),u=typeof t.journal_generation=="string"&&t.journal_generation.length>0?t.journal_generation:void 0,f=t.journal_ordinals&&typeof t.journal_ordinals=="object"&&!Array.isArray(t.journal_ordinals)?t.journal_ordinals:void 0,p=t.entry_times&&typeof t.entry_times=="object"&&!Array.isArray(t.entry_times)?t.entry_times:void 0,h="journal_generation"in t||"journal_ordinals"in t||"entry_times"in t,g=s.journalPeerSource===!0||h,m=g&&u!==void 0&&u===s.journalGeneration,y=d.map(R=>String(R.id??"")).filter(R=>R.length>0&&R.length<=128),_={entries:d.map(R=>{const M=String(R.id??""),G=f?.[M],A=p?.[M];return{id:M,ts:m&&typeof A=="number"&&Number.isFinite(A)?A:n/1e3,type:"message",payload:{kind:R.custom_type?"custom":"message",...R},...m&&fr(G)?{journal_seq:G}:{}}}),has_more:s.hasMore,...m?{journal_generation:u}:{}};let b=Yn(s,_,{replace:t.reset===!0,statedByOwner:t.reset===!0,peerSource:g});if(g&&y.length>0)if(m){const R=y.filter(M=>!fr(f?.[M]));R.length>0&&(b=dc(b,R))}else b=dc(b,y),u!==void 0&&(b=Rn(b,{journal_generation:u,journal_order_state:"ready"},[],!1,void 0,{peer:!0}),b=br(b,!0));return b}case"tool_call_compose":{const l=String(t.tool_call_id??"");if(!l)return s;const d=String(t.supersedes_tool_call_id??""),u=`tool:${l}`,f=s.records[s.index.get(u)??-1],p=d?s.records[s.index.get(`tool:${d}`)??-1]:void 0,h=f?.kind==="tool"?f:p?.kind==="tool"?p:void 0;if(h&&h.phase!=="composing"&&h.phase!=="queued")return d&&f?.kind==="tool"?Ys(s,d):s;const m=String(t.not_run_reason??"").trim()||null,y=String(t.not_run_kind??"").trim()||null;if(lc(t.tool_name,c)&&!m&&!h)return d?Ys(s,d):s;const _=Number(t.argument_bytes??0),b={kind:"tool",id:u,ts:h?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:m?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:_>0?_:h?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Vn,added:0,removed:0,diff:null,stopped:!1,notRunReason:m,notRunKind:m?y:null,neverSent:m!==null};return d&&p?.kind==="tool"&&f?.kind!=="tool"?Cy(s,d,b):ge(d&&f?.kind==="tool"?Ys(s,d):s,b)}case"tool_execution_start":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(u&&u.kind==="tool"&&u.phase==="done"&&!u.notRunReason)return s;const f=oc(s,l,t,u),p=f&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:f,anchoredAt:_n(t)??n}):s.argsByCall,h=p===s.argsByCall?s:{...s,argsByCall:p};return lc(t.tool_name,c)&&!u?h:ge(h,{kind:"tool",id:d,ts:u?.ts??n,toolCallId:l,toolName:String(t.tool_name??""),intent:t.intent??(typeof f?.i=="string"?f.i:null),args:f,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:_n(t)??(u?.kind==="tool"&&u.startedAt!==null?u.startedAt:n),endedAt:null,images:u?.kind==="tool"?u.images:Vn,added:0,removed:0,diff:u?.kind==="tool"?u.diff:null,details:u?.kind==="tool"?u.details??null:null,stopped:!1})}case"tool_execution_update":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1];if(!u||u.kind!=="tool")return s;const f=t.partial_result??{},p=ki(f.details,u.details);return p===(u.details??null)?s:ge(s,{...u,details:p})}case"tool_execution_end":{const l=String(t.tool_call_id??"");if(!l)return s;const d=`tool:${l}`,u=s.records[s.index.get(d)??-1],f=t.result??{};if(Cd(f.details))return Nd(s,d);const p=oc(s,l,t,u),h=u&&u.kind==="tool"?u:{kind:"tool",id:d,ts:n,toolCallId:l,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:Vn,added:0,removed:0,diff:null,stopped:!1},g=p&&!s.argsByCall.has(l)?new Map(s.argsByCall).set(l,{arguments:p,anchoredAt:_n(t)??n}):s.argsByCall,m=g===s.argsByCall?s:{...s,argsByCall:g},y=r.userStoppedAt??null,_=!!(t.is_error??f.is_error),b=hd(f.details?.__fault),R=y!==null&&(typeof h.startedAt=="number"?h.startedAt<=y:_);return ge(m,{...h,args:p,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:ft(f)||null,isError:R||b?!1:_,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof h.startedAt=="number"?h.startedAt+t.duration_s*1e3:null,startedAt:null,images:Ry(Zt(f,d,h.images),h.images),...nd(f.details,h),diff:td(ed(f.details),h.diff),stopped:h.stopped||R||b,delivery:Kl(f.details,h.delivery),details:ki(f.details,h.details)})}case"supplement_progress":{const l=gy(t);if(!l)return s;const d=uo(l.anchor),u=s.records[s.index.get(d)??-1],f=u&&u.kind==="supplement"?u:null,p=pd(f,l,n);return p?ge(s,p):s}case"notice":{const l=String(t.text??"");if(!l)return s;const d=`notice:${s.generation}:${l}`;return s.index.has(d)?s:ge(s,{kind:"notice",id:d,ts:n,text:l,level:t.kind??"info"})}case"compaction_end":{const l=Number(t.tokens_before??0),d=Number(t.tokens_after??0),f=!!t.success?null:vd(String(t.detail??"")),p=f?f.text:l&&d?Oy(l,d):bd,h=`compaction:${s.generation}:${l}:${d}`,g=s.compacting?{...s,compacting:!1,compactingSince:0}:s;return g.index.has(h)?g:f?ge(g,{kind:"notice",id:h,ts:n,text:p,level:f.level}):jy(ge(g,{kind:"compaction",id:h,ts:n,text:p,before:l}))}case"retry_start":{const l=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,d=`retry:${s.generation}:${String(t.attempt??"")}`;return s.index.has(d)?s:ge(s,{kind:"notice",id:d,ts:n,text:l,level:"warning"})}case"subagent_end":{const l=`subagent:${String(t.job_id??"")}`,d=String(t.status??""),u=`${String(t.label??"Subagent")} ${d||"finished"}`,f=s.records[s.index.get(l)??-1];return f&&f.kind==="notice"&&f.text===u?s:ge(s,{kind:"notice",id:l,ts:f?.ts??n,text:u,level:d==="failed"?"error":"info"})}default:return s}}function _n(e){return Gh(e.started_at_epoch)}function vo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function u_(e){const t=vo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function f_(e,t){const n=_n(e);if(n!==null)return n;const r=vo(e);if(!r)return null;const s=t.argsByCall.get(r)?.anchoredAt;return typeof s=="number"&&Number.isFinite(s)&&s>0?s:null}function p_(e,t){if(_n(e)!==null)return!1;const n=vo(e);if(!n)return!1;const r=t.argsByCall.get(n)?.anchorId;if(typeof r!="string")return!1;const s=t.index.get(r);return s!==void 0&&s<=_d(t.records)}function bo(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 gs(e){return e.type==="tool_execution_end"}function h_(e,t,n=Date.now(),r=null){let s=e;t.streaming&&t.generation>s.generation&&(s={...s,generation:t.generation}),s.compacting&&(s={...s,compacting:!1,compactingSince:0});const i=t.streaming===!0,a=Td(t);let c=!1;const l=new Set;for(const u of t.live_events??[]){const f=u;let p=n;const h=u_(f);if(h!==null&&!s.index.has(h)){const g=f_(f,s);if(g!==null)p=g,c=!0,p_(f,s)&&l.add(h);else if(gs(f)||bo(f)||!i)continue}s=Ti(s,f,p,{seed:!0,queuedAskEngine:a,...r?{frame:r}:{}})}if(!c)return s;const d=ur(s.records,l,s);return{...s,records:d,index:Ke(d)}}function fc(e){const t=new Map;for(const n of e??[]){if(!n)continue;const r=n;if(!gs(r)&&!bo(r))continue;const s=String(r.tool_call_id??"");if(!s)continue;const i=_n(r);i!==null&&t.set(s,i)}return t}function m_(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n;if(r.type!=="tool_call_compose")continue;const s=r.not_run_reason;if(typeof s=="string"&&s.trim().length>0)continue;const i=String(r.tool_call_id??"");i&&t.add(i)}return t}const g_=5e3;function y_(e,t){const n=new Set(t),r=new Map;if(n.size===0)return r;for(const s of e){if(s.payload?.role!=="tool")continue;const i=s.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const a=s.ts;typeof a!="number"||!Number.isFinite(a)||r.set(i,Math.round(a*1e3))}return r}function __(e,t,n,r=new Map,s=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let a=null;for(const l of t){const d=n.get(l);if(d===void 0){if(s.has(l))continue;return!1}(a===null||d<a)&&(a=d)}for(const l of r.values())(a===null||l<a)&&(a=l);return a===null?!1:Math.round(i*1e3)<=a-g_}function pc(e,t){const n=[];for(const r of e??[]){if(!r)continue;const s=r;if(!gs(s)&&!bo(s))continue;const i=String(s.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function hc(e,t,n,r){const s=[],i=new Set;for(const a of t)i.has(a)||(i.add(a),!n.has(a)&&((e.get(a)??0)>=r||s.push(a)));return s}const v_=3.25,Ci=100,wo=500;function mc(e){return e<=0?Ci:Math.min(wo,Ci+Math.ceil(v_*e))}function Js(e,t){const n=[];if(t.size===0)return n;for(const r of e){const s=r.payload?.tool_calls;if(Array.isArray(s))for(const i of s)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function b_(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function w_(e,t){const n=new Set(t);for(const i of e){const a=i.payload?.tool_calls;if(Array.isArray(a))for(const c of a)c&&typeof c.id=="string"&&n.add(c.id)}const r=[],s=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const a=i.payload.tool_call_id;typeof a!="string"||n.has(a)||s.has(a)||(s.add(a),r.push(a))}return r}function S_(e,t){return e&&t===0}function k_(e){const t=new Set;for(const n of e??[]){if(!n)continue;const r=n,s=r.not_run_reason,i=r.type==="tool_call_compose"&&typeof s=="string"&&s.trim().length>0;if(r.type!=="tool_execution_start"&&!gs(r)&&!i)continue;const a=String(r.tool_call_id??"");a&&t.add(a)}return t}function Md(e,t,n){const r=new Set(e),s=[];for(const i of t)!r.has(i)&&!n.has(i)&&s.push(i);for(const i of e){if(n.has(i))return s;t.has(i)&&s.push(i)}return s}function R_(e,t,n){return Md(e,t,n).length}function gc(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=ge(t,{...n,truncated:"interrupted"}));return t}function E_(e,t=Date.now()){return e.records.length===0?e:{...st,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function I_(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 yc(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function x_(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return mo(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function os(e,t){let n=t;for(const r of e.records)r.ts>n&&(n=r.ts);return n}function Dd(e,t,n,r,s=Date.now(),i=Ii){if(e.index.has(t))return e;const a=ms(n);return ge(e,{kind:"user",id:t,ts:os(e,s),text:n,images:r,...i.length?{documents:i}:{},...a?{skill:a}:{},local:!0,provisional:!0})}function Nd(e,t){return mo(e,n=>n.id===t)}let _c=0;function T_(e,t,n,r=Date.now()){return _c+=1,ge(e,{kind:"notice",id:`local:${r}:${_c}`,ts:os(e,r),text:t,level:n})}function ER(e,t,n,r){const s=t?.anchor_id,i=t?.kind;return!s||i!=="error"&&i!=="interrupted"&&i!=="closed"&&i!=="retired"||n||e.index.has(s)||!t?.unseen&&!r?.has(s)?e:(r?.add(s),ge(e,{kind:"notice",id:s,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="closed"?Sd:i==="retired"?kd:i==="error"?"Stopped with an error":"Interrupted",level:i==="closed"?"info":i==="retired"?"warning":i==="error"?"error":"warning"}))}const C_="compacting context…";function IR(e){return typeof e=="string"&&e.trim()===C_}const A_=[1500,5e3];async function xR(e,t=n=>new Promise(r=>setTimeout(r,n))){for(const n of A_){await t(n);try{if(await e())return}catch{}}}function O_(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 vc=new Set(["openrouter","radient","radient-key"]),P_=new Set(["auto","openrouter/auto"]),j_="Auto";function Ld(e){return e.slice(e.lastIndexOf("/")+1)||e}function M_(e,t){return e===t||e===Ld(t)}function Xs(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 TR(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,r=typeof e.display_name=="string"?e.display_name.trim():"",s=vc.has(t)||!r||M_(r,e.model_id)||r.toLowerCase()==="unknown";return{name:vc.has(t)&&P_.has(e.model_id)?j_:s?Ld(n):r,selector:n}}function CR(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function AR(e){return e?.supports_fast_mode!==!0?null:e.fast_mode===!0?"on":"off"}function OR(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function PR(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 jR(e){const t=e?.effort_displacement,n=t?.note;if(typeof n!="string"||!n.trim())return null;const r=new Map;for(const a of[e?.effective_model,e?.selected_model]){const c=typeof a?.display_name=="string"?a.display_name.trim():"";if(!a||!c||!a.provider||!a.model_id)continue;const l=`${a.provider}/${a.model_id}`;l!==t?.serving&&l!==t?.selected||r.set(l,c)}if(!r.size)return n.trim();const s=[...r.keys()].sort((a,c)=>c.length-a.length).map(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=new RegExp(`(^|[\\s(])(${s.join("|")})(?=$|[\\s;,)\\]}]|\\.(?=\\s|$))`,"g");return n.trim().replace(i,(a,c,l)=>`${c}${r.get(l)}`)}function MR(e){const t=e?.effort_displacement?.chosen;return typeof t=="string"&&t.trim()?t.trim().toLowerCase():null}function DR(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 $d(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 NR(e,t){const n=(e??t)?.effective_model;return $d(n)?null:n?.model_id??null}function LR(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,r=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",s=$d(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${r?` (${r})`:""}. It offers ${n.join(", ")}.`}:s?{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&&r?{label:r,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 $R(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(r=>typeof r=="object"&&r!==null&&"value"in r?String(r.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:`Reasoning effort. This model offers ${n.join(", ")}.`}}function D_(e,t){const n=e?.model_access;if(n&&typeof n.effective_state=="string"){const a=Ln(n.provider);if(!a)return null;const c=Ln(e?.selected_model?.provider);if(c&&c!==a)return null;const d=["local","pending","eligible_borrow_unverified","effective_borrow","expired","withdrawn","owner_unavailable","device_bound","absent"].includes(n.effective_state)?n.effective_state:"pending";return d==="local"?null:{...d==="absent"?{connectHere:t==="local"}:{},provider:a,label:Ln(n.label)||a,effectiveState:d,owner:Ln(n.owner_label)||Ln(n.owner_device)||"the owner device",observedAt:qs(n.observed_at),lastGrantAt:qs(n.last_grant_at),lastGrantExpiresAt:qs(n.last_grant_expires_at)}}if(!n||n.state!=="signed_out"&&n.state!=="temporarily_unavailable")return null;const r=typeof n.provider=="string"?n.provider:"";if(!r)return null;const s=e?.effective_model?.provider;if(s&&s!==r)return null;const i=typeof n.label=="string"&&n.label.trim()!==""?n.label:r;return n.state==="temporarily_unavailable"?{provider:r,label:i,state:n.state}:{provider:r,label:i}}function UR(e,t){if(!t)return;const n=e.find(r=>r.session_id===t)?.locality;return n==="local"||n==="remote"?n:void 0}function FR(e){return e&&e.draft!==!0?D_(e.frontend,e.servingLocality):null}function Ln(e){return typeof e=="string"?e.trim():""}function qs(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=864e10?e:void 0}function ei(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e*1e3))}function BR(e){const{label:t,effectiveState:n}=e,r=e.owner||"the owner device",s={local:[`${t} access available`,"This session uses its own provider access."],pending:[`Checking ${t} access`,"Access has not converged yet. The next request checks the owner automatically; no additional sign-in is needed here."],eligible_borrow_unverified:[`Checking access from ${r}`,`This session may borrow ${t} access, but it has not resolved it yet. The next request verifies ${r} automatically.`],effective_borrow:[`${t} access from ${r}`,"The runtime resolved borrowed access for this session. Every new request checks the owner again."],expired:[`Fresh ${t} access needed`,`The last borrowed grant expired, but borrowing permission is still present. The next request asks ${r} for fresh access automatically.`],withdrawn:[`${t} access needs attention`,"The owner cannot currently provide borrowed access, or borrowing permission is unavailable. Restore owner access or permission before retrying, or choose another model."],owner_unavailable:[`${r} cannot provide access`,`This session could not resolve ${t} access from ${r}. Previous access cannot be reused. Retry after owner access is restored, or choose another model.`],device_bound:[`${t} needs a device sign-in`,"This login cannot be borrowed. Sign in on the device running this session, or choose another model."],absent:[`No ${t} access`,e.connectHere===!0?"The serving device has no effective provider access for this session. Connect an account or choose another model.":"The device running this session has no effective provider access. Sign in or restore access on that device, or choose another model."]},i=e.state==="temporarily_unavailable",[a,c]=n?s[n]:[i?`${t} is temporarily unavailable`:`Not signed in to ${t}`,i?"Your saved sign-in is still present. Try again later or choose another model.":`This session runs ${t} without a working sign-in, so it cannot answer until you connect it.`],l=[];return n&&e.observedAt!==void 0&&l.push(`Last checked: ${ei(e.observedAt)}.`),n&&e.lastGrantAt!==void 0&&l.push(`Last resolved: ${ei(e.lastGrantAt)}.`),n&&e.lastGrantExpiresAt!==void 0&&l.push(`Recorded grant expiry: ${ei(e.lastGrantExpiresAt)}.`),n&&(e.lastGrantAt!==void 0||e.lastGrantExpiresAt!==void 0)&&l.push("History only; not permission to reuse access."),{title:a,description:c,history:l.join(" "),tone:n==="effective_borrow"?"neutral":"warning",canConnect:n?n==="absent"&&e.connectHere===!0:!i,canSwitchModel:n!=="effective_borrow"}}function GR(e){return e.kind==="needs-sign-in"||e.kind==="signing-in"||e.kind==="settled"&&e.canRetry}function HR(e){return e?.provider==="radient"&&e.effectiveState!==void 0&&(e.effectiveState!=="absent"||e.connectHere!==!0)}function WR(e,t){return t&&e.provider==="radient"&&(e.effectiveState===void 0||e.effectiveState==="absent"&&e.connectHere===!0)}function N_(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function L_(e,t){return!!e.streams[t]}function Ud(e,t){return e.attached[t]?.turns.at(-1)}function zR(e,t){const n=Ud(e,t);return n?e.streams[n.asideId]:void 0}function ZR(e,t){const n=e.attached[t]?.turns??[];for(let r=n.length-1;r>=0;r-=1){const s=n[r];if(s&&e.streams[s.asideId]?.settled)return s.asideId}}function $_(){return{text:"",streaming:!0,settled:!1,error:null}}function U_(e){return{text:e,streaming:!1,settled:!0,error:null}}function F_(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const B_=vr(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const r=n.attached[t];return r&&r.notice===null?n:{attached:{...n.attached,[t]:r?{...r,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,r)=>e(s=>({streams:{...s.streams,[n]:$_()},attached:{...s.attached,[t]:{turns:[...s.attached[t]?.turns??[],{asideId:n,question:r}],notice:null}}})),applyAsideDelta:(t,n)=>e(r=>{const s=N_(r.streams[t],n);return s?{streams:{...r.streams,[t]:s}}:r}),settleAside:(t,n)=>e(r=>r.streams[t]?{streams:{...r.streams,[t]:U_(n)}}:r),failAside:(t,n)=>e(r=>L_(r,t)?{streams:{...r.streams,[t]:F_(r.streams[t],n)}}:r),setAsideNotice:(t,n)=>e(r=>{const s=r.attached[t];return s?{attached:{...r.attached,[t]:{...s,notice:n}}}:r}),queueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];return i?{attached:{...s.attached,[t]:{...i,notice:null,queued:{asideId:n,messageIds:[...r]}}}}:s}),unqueueAdoption:(t,n,r)=>e(s=>{const i=s.attached[t];if(i?.queued?.asideId!==n)return s;const{queued:a,...c}=i;return{attached:{...s.attached,[t]:{...c,notice:r}}}}),detachAside:t=>e(n=>{const r=n.attached[t],s={...n.attached};if(delete s[t],!r)return{attached:s};const i={...n.streams};for(const a of r.turns)delete i[a.asideId];return{streams:i,attached:s}})}));function VR(e,t){return Ud(e,t)?.asideId}const G_=4*1024*1024,bc=1024*1024,pt=new Map;function wc(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function H_(e){const t=e.slice(-200),n=wc(t);if(n<=bc)return{records:t,bytes:n};let r=0,s=t.length,i=0;for(;s-r>1;){const a=Math.floor((r+s)/2),c=wc(t.slice(a));c>bc?r=a:(s=a,i=c)}return{records:t.slice(s),bytes:i}}function W_(e,t){const{records:n,bytes:r}=H_(x_(t.transcript).records);if(n.length===0){pt.delete(e);return}const s={...t.transcript,records:n,index:new Map(n.map((a,c)=>[a.id,c])),oldestId:null,oldestTs:0,hasMore:!1,argsByCall:new Map},i={transcript:s,savedAt:Date.now(),bytes:r,owedLabels:Sc(n,t.owedLabels),markLabels:Sc(n,t.markLabels),replayBorn:new Set([...t.replayBorn??[]].filter(a=>s.index.has(a)))};pt.delete(e),pt.set(e,i),Z_()}function Sc(e,t){if(!t||t.size===0)return kc;const n=new Set;for(const r of e)r.kind!=="tool"||r.args||r.toolCallId&&t.has(r.toolCallId)&&n.add(r.toolCallId);return n.size>0?n:kc}const kc=new Set;function Fd(e){const t=pt.get(e);if(!t)return null;const{bytes:n,...r}=t;return r}function z_(e){pt.delete(e)}function Z_(){let e=0;for(const t of pt.values())e+=t.bytes;for(;e>G_&&pt.size>0;){const t=pt.keys().next().value;if(t===void 0)break;const n=pt.get(t);pt.delete(t),e-=n?.bytes??0}}const V_=8,K_=128,Bd=new Set,Y_="",bt=new Map,So=e=>e??Y_;function KR(e){return bt.get(So(e))??Bd}function YR(e,t,n){const r=So(e),s=bt.get(r)??new Set,i=new Set(s);if(n)for(i.delete(t),i.add(t);i.size>K_;){const a=i.values().next().value;if(a===void 0)break;i.delete(a)}else i.delete(t);for(bt.delete(r),i.size>0&&bt.set(r,i);bt.size>V_;){const a=bt.keys().next().value;if(a===void 0)break;bt.delete(a)}return bt.get(r)??Bd}function Q_(e){bt.delete(So(e))}const J_=128,as=4096,ti=e=>({complete:e===null,owners:new Map,keys:new Map,reason:e}),Rc=e=>e.startsWith("qg:")&&e.length>3;function QR(e,t,n=null,r=[]){const s=new Map,i=new Map;for(let c=0;c<e.length;c+=1){const l=e[c];for(let d=0;d<l.segmentIds.length;d+=1){const u=l.segmentIds[d];if(s.has(u))return ti("duplicate-prior-id");if(s.size===as)return ti("prior-id-limit");s.set(u,{ordinal:c,order:d})}l.eligible!==!1&&Rc(l.key)&&t.has(l.key)&&i.size<J_&&i.set(c,l.key)}for(const c of r)if(!s.has(c)){if(s.size===as)return ti("prior-id-limit");s.set(c,{ordinal:-1,order:-1})}const a=n===null?void 0:s.get(n);if(a!==void 0&&a.ordinal>=0){const c=e[a.ordinal];c.eligible!==!1&&Rc(c.key)&&i.set(a.ordinal,c.key)}return{complete:!0,owners:s,keys:i,reason:null}}function JR(e,t,n={}){const r=f=>({episodes:[...t],reason:f});if(!e.complete)return r(e.reason??"incomplete-prior");if(e.owners.size>as)return r("prior-id-limit");const s=new Set,i=n.currentIdsUnique===!0?null:new Set,a=new Map,c=new Map,l=(f,p,h)=>{const g=a.get(f);g===void 0?a.set(f,{current:p,many:!1,lastOrder:h,reordered:!1,outside:!1}):(g.current!==p&&(g.many=!0),h<=g.lastOrder&&(g.reordered=!0),g.lastOrder=h)};for(let f=0;f<t.length;f+=1){const p=t[f];let h=null,g=!1;for(const y of p.segmentIds){if(i!==null){if(i.has(y))return r("duplicate-current-id");if(i.size===as)return r("current-uniqueness-unproved");i.add(y)}const _=e.owners.get(y);if(_!==void 0){if(s.has(y))return r("duplicate-current-id");s.add(y),l(_.ordinal,f,_.order),h===null?h=_.ordinal:h!==_.ordinal&&(g=!0)}}if(p.eligible===!1||g||h===null||h<0)continue;const m=e.keys.get(h);m!==void 0&&c.set(f,{owner:h,key:m})}for(const f of n.outsideCurrentIds??[]){const p=e.owners.get(f);if(p===void 0||s.has(f))continue;const h=a.get(p.ordinal);h!==void 0&&(h.outside=!0)}for(const[f,p]of c){const h=a.get(p.owner),g=p.key.slice(3);(h===void 0||h.many||h.reordered||h.outside||!s.has(g))&&c.delete(f)}const d=new Set(e.keys.values()),u=new Set;for(let f=0;f<t.length;f+=1){const p=c.get(f)?.key??t[f].key;if(d.has(p)){if(u.has(p))return r("key-collision");u.add(p)}}return{episodes:t.map((f,p)=>{const h=c.get(p);return h===void 0?f:{...f,key:h.key}}),reason:null}}const X_=8,q_="",zt=new Map,ko=e=>e??q_;function XR(e){return zt.get(ko(e))??null}function qR(e,t){const n=ko(e);for(zt.delete(n),zt.set(n,t);zt.size>X_;){const r=zt.keys().next().value;if(r===void 0)break;zt.delete(r)}}function ev(e){zt.delete(ko(e))}function tv(){let e=null;const t=async(n,r)=>{n.setLoading?.(!0);const s=n.getTranscript().orderRevision??0,i=()=>(n.getTranscript().orderRevision??0)===s;try{let a=r,c=await n.readPage(a);if(!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing){const u=s_(n.getTranscript()),f=u!==null&&u!==a?u:n_(c,a);if(f===null)return{kind:"failed",reason:"cursor-missing"};if(a=f,c=await n.readPage(a),!n.isCurrent()||!i())return{kind:"stale"};if(c.cursor_missing)return{kind:"failed",reason:"cursor-missing"}}let l=n.getTranscript();const d=n.commit(u=>(l=u,(u.orderRevision??0)!==s?u:Yn(u,c,{...u.oldestId===r?{pagedBefore:a}:{},...n.peerSource?.()===!0?{peerSource:!0}:{}})));return(d.orderRevision??0)!==s||c.journal_generation!==void 0&&c.journal_generation!==d.journalGeneration?{kind:"stale"}:{kind:"applied",newRecords:Math.max(0,d.records.length-l.records.length),exhausted:!d.hasMore}}catch{return{kind:"failed",reason:"request"}}finally{n.setLoading?.(!1)}};return{busy:n=>e!==null&&e.key===n,load(n,r){if(e!==null&&e.key===n)return e.promise;const s=r.getTranscript();if(!s.hasMore||!s.oldestId)return Promise.resolve({kind:"nothing-to-load"});const i={key:n,promise:t(r,s.oldestId)};e=i;const a=()=>{e===i&&(e=null)};return i.promise.then(a,a),i.promise}}}const nv=new Set(["subagent_start","subagent_progress","subagent_end"]),rv=(e,t)=>({...e,[t]:(e[t]??0)+1}),sv=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const r=Gd(n);r&&(t[r]=(t[r]??0)+1)}return t},Gd=e=>{if(!e||typeof e!="object")return null;const t=e;return nv.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},iv=(e,t)=>{const n=Gd(t);return n?rv(e,n):e};function Ec(e,t,n){if(!n||!e)return{};const r=e.context_tokens;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return{};const s=t.context_tokens;return typeof s=="number"&&Number.isFinite(s)&&s>=r?{}:{context_tokens:r,context_is_estimate:e.context_is_estimate??t.context_is_estimate,context_window:e.context_window??t.context_window,last_usage:e.last_usage??null}}function ov(e){for(const t of e)t.type==="aside_delta"&&B_.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function av(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const Ht=new Set,Hn=new Set;function cv(e,t){let n=null;for(const r of t)e.has(r)&&(n=n??new Set(e),n.delete(r));return n??e}const lv=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),dv=15e3,Ai=[500,1e3,2e3,4e3,8e3,8e3],uv=Ai.length,fv=2e4,pv=1e4,hv=1e4;function Ic(e){const t=Math.max(1,Math.min(e,Ai.length));return Ai[t-1]??8e3}const mv=3,gv=250,yv=32*1024,xc=512,Tc=new Set(["turn_end","agent_end"]),Cc=2,_v=500,Ac=wo,vv=6,ni=Il("sessions.history"),bv=2e3,Oc={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},Yt=new Map,zr=new Map,wv=8,Sv=2048,Pc=1024,kv=1024,Rv="",Bt=new Map;function jc(e){const t=e??Rv,n=Bt.get(t);if(n)return Bt.delete(t),Bt.set(t,n),n;const r={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(Bt.set(t,r);Bt.size>wv;){const s=Bt.keys().next().value;if(s===void 0||s===t)break;Bt.delete(s)}return r}function ri(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function si(e,t,n,r){return t.has(n)?!1:e.inFlight.has(n)?!0:r}function Ev(e,t){return zr.set(e,t),()=>{zr.get(e)===t&&zr.delete(e)}}function eE(e){const t=zr.get(e);return t?(t(),!0):!1}const Re=new Map,Iv=4,xv=16;function Hd(e,t){e(n=>Dd(n,t.id,t.text,t.images,void 0,t.documents)),t.painted||(t.painted=!0,t.onPainted?.())}function Tv(e,t,n){const r=e.index.get(t),s=r===void 0?void 0:e.records[r];if(r===void 0||!s||s.kind!=="user"||!s.local||s.text===n)return e;const i=e.records.slice(),{skill:a,...c}=s,l=ms(n);return i[r]=l?{...c,text:n,skill:l}:{...c,text:n},{...e,records:i}}function Oi(e,t){let n=Re.get(e);if(!n){if(Re.size>=xv){const i=Re.keys().next();i.done||Re.delete(i.value)}n=new Map,Re.set(e,n)}const r={identity:e,id:t.id,text:t.text,images:t.images,documents:t.documents??[],onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(r.id,r);n.size>Iv;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const s=Yt.get(e);s&&Hd(s,r)}function tE(e){if(!e)return null;const t=Re.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function Pi(e,t){const n=Re.get(e);n&&(n.delete(t),n.size===0&&Re.delete(e))}function ji(e,t){const n=Re.get(e)?.get(t);n&&(n.settled=!0)}function Mc(e,t){return e?Re.get(e)?.has(t)===!0:!1}function nE(e){return e?(Re.get(e)?.size??0)>0:!1}function Cv(e,t,n){const r=Re.get(e)?.get(t);if(!r)return;r.text=n;const s=Yt.get(e);s&&s(i=>Tv(i,t,n))}function Av(e,t){if(e===t)return;const n=Re.get(e);if(!n)return;Re.delete(e);const r=Re.get(t)??new Map;for(const[s,i]of n)i.identity=t,r.set(s,i);Re.set(t,r)}function Ur(e){Re.delete(e)}function Ov(e,t){const n=Re.get(e);if(n)for(const r of[...n.keys()]){const s=t.index.get(r),i=s===void 0?void 0:t.records[s];i?.kind==="user"&&i.local!==!0&&Pi(e,r)}}function Pv(e,t){Yt.set(e,t);const n=Re.get(e);if(n)for(const r of n.values())Hd(t,r);return()=>{Yt.get(e)===t&&Yt.delete(e)}}function jv(e,t){const n=Re.get(e);if(!n)return t;let r=t;for(const s of n.values())r=Dd(r,s.id,s.text,s.images);return r}function Mv(e,t,n){return e===t?!0:!n}function Dv(e,t){const n=Yt.get(e);if(!n)return Pi(e,t),"queued";let r="queued";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"?s:i.local?(r="retracted",Nd(s,t)):(r="owner",s)}),Pi(e,t),r}function Wd(e,t){const n=Yt.get(e);if(!n)return"unseen";let r="unseen";return n(s=>{const i=s.records[s.index.get(t)??-1];return!i||i.kind!=="user"||(r=i.local?"local":"owner"),s}),r}function Nv(e){const t=Fd(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:st,stale:!1,owedLabels:Ht,markLabels:Hn}}function Lv(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function ii(e,t){if(e.size!==0)for(const n of t)e.delete(rt(n))}function Fr(e,t){for(const n of t)e.add(rt(n))}function rE(e,t,n=!0,r=e,s={}){const i=s.openFrame===!0,a=s.journalOrder===!0,c=v.useRef(a);c.current=a;const l=v.useRef(i);l.current=i;const d=s.peerJournalSource===!0,u=v.useRef(d);u.current=d;const f=v.useRef(null),p=v.useRef(0),h=v.useRef(0),g=v.useRef(0),m=v.useRef(null),y=v.useRef(null),_=v.useCallback(()=>{if(!e||!c.current||!u.current)return!1;const T=ze.getState();return Eb(T.sessions,T.placementFacts,e)},[e]),b=v.useCallback(()=>{const T=f.current;return _()&&T!==null&&T.sessionId===e&&T.peer},[_,e]),R=v.useCallback(()=>{const T=f.current;return T!==null&&T.sessionId===e&&T.peer},[e]),[M,G]=v.useState(()=>{const T=t&&e?Nv(e):null;return{status:"connecting",frontend:null,heldFrontend:null,contextCarried:!1,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:r?jv(r,T?.transcript??st):st,stale:T?.stale??!1,missing:!1,loadingOlder:!1,olderFailed:!1,subagentPulses:{},labelPending:T?.owedLabels??Ht,labelMarked:T?.markLabels??Hn,labelHoldLate:!1,hydrated:!1,historyReadPending:!1}}),A=v.useRef(M),O=v.useCallback(T=>{const K=T(A.current);return K===A.current||(A.current=K,G(K)),K},[]),S=v.useRef(e),U=v.useRef([]),V=v.useRef(st.index),ce=v.useRef(new Set),x=v.useRef(new Set),C=v.useRef(jc(e)),re=v.useRef(new Set),je=v.useRef(null),xn=v.useRef({}),Is=v.useRef(null),xs=v.useRef(null),Ts=v.useRef(null),Tn=v.useRef(0),Xe=v.useRef(0);v.useEffect(()=>{if(!e||!t)return;const T=++Xe.current,K=new WeakMap,se=(W,z)=>{const Y=K.get(W);if(Y===void 0||Ye(z)===Y.revision)return!1;const ee=W.payload.history.journal_generation;return!(typeof ee=="string"&&ee.length>0&&ee===z.journalGeneration)};let pe=null,H=!1,we=0,$e=0,ue=0,me=0,D=0,he=0,oe=0,Ee=!1;const Se=()=>{he&&(window.clearTimeout(he),he=0)},Te=W=>{for(const z of W)C.current.attempts.set(z,(C.current.attempts.get(z)??0)+1)},sn=W=>{O(z=>{const Y=new Set;for(const q of z.labelPending)z.labelPending.has(q)&&(si(C.current,z.transcript.argsByCall,q,ri(z))||Y.add(q));let ee=null;for(const q of z.labelMarked)si(C.current,z.transcript.argsByCall,q,ri(z))||(ee=ee??new Set(z.labelMarked),ee.delete(q));if(Y.size===0&&!ee)return z;const ie=new Set(z.labelPending);for(const q of Y)ie.delete(q);return{...z,labelPending:ie.size?ie:Ht,labelMarked:ee&&ee.size===0?Hn:ee??z.labelMarked}})},Zu=W=>{O(z=>{let Y=null,ee=null;for(const ie of W)z.labelPending.has(ie)&&(Y=Y??new Set(z.labelPending),Y.delete(ie),ee=ee??new Set(z.labelMarked),ee.add(ie));return!Y||!ee?z:{...z,labelPending:Y.size?Y:Ht,labelMarked:ee}})},Ir=async(W,z,Y=Oc,ee=1,ie,q=z,Be=null)=>{Tn.current+=1,Xe.current===W&&O(Ie=>Ie.historyReadPending?Ie:{...Ie,historyReadPending:!0});for(const Ie of Y.targets)C.current.inFlight.add(Ie),re.current.add(Ie);let Me=!1;try{Me=await Vu(W,z,q,Be,Y,ee,ie)}finally{if(Tn.current=Math.max(0,Tn.current-1),Tn.current===0&&O(Ie=>Ie.historyReadPending?{...Ie,historyReadPending:!1}:Ie),!Me){for(const Ie of Y.targets)C.current.inFlight.delete(Ie);C.current.refused&&Zu(Y.targets),sn()}}},Vu=async(W,z,Y,ee,ie,q,Be)=>{const Me={keys:new Set,oldest:null,hasMore:!1,joined:!1,reachedHeld:Y.size===0},Ie=A.current.transcript.viewEpoch,Ce=await Ku(W,z,Y,ee,ie,q,Me,Be);if(Ce||Xe.current!==W||Me.reachedHeld||A.current.transcript.viewEpoch!==Ie)return Ce;const Ge=z!==Y&&[...z].some(We=>Y.has(We));if(Ge&&Me.joined)return Ce;let He;if(Me.oldest){if(!Me.hasMore)return Ce;He={id:Me.oldest.id,ts:Math.round((Me.oldest.ts??0)*1e3)}}else{if(Ge||!ee)return Ce;He=ee}if(!He)return Ce;const It=O(We=>{const et=d_(We.transcript,He,Me.keys);return et===We.transcript?We:{...We,transcript:et}});return V.current=It.transcript.index,Ce},Ku=async(W,z,Y,ee,ie,q,Be,Me)=>{const Ie=A.current.transcript.viewEpoch,Ce=()=>A.current.transcript.viewEpoch!==Ie,Ge=new Set;let He,It=0,We=0,et=!1,xt=Y.size===0,on=!1;const xr=A.current.cold,tt=new Set(ie.found),lt=()=>R_(ie.order,ie.targets,tt),Tr=()=>Md(ie.order,ie.targets,tt),Ps=()=>{const $=new Map;for(const be of w){if(tt.has(be))continue;const le=fe.get(be);le!==void 0&&$.set(be,le)}return $},E=new Set(ie.every);for(const $ of tt)E.add($);const w=new Set,fe=new Map;let ve=1;const De=ie.targets.size>0;let Z=Math.max(mc(lt()),De?C.current.depth:0),jn=0;for(;It<Ac&&We<vv;){We+=1;let $;const be=wi(A.current.transcript),le=be.revision;try{$=await xe({op:"sessions.history",sessionId:e,...He?{beforeId:He}:{},limit:Math.min(Z,Ac-It),openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}})}catch{if(Ce())return!1;if(A.current.transcript.records.length>0){if(jn++>0)return C.current.refused=!0,!1;continue}return q<mv?(D=window.setTimeout(()=>{if(D=0,Xe.current!==W||Ce()){sn();return}Ir(W,z,ie,q+1,Me,Y,ee)},Ic(q)),!0):(O(de=>({...de,status:"unavailable",failure:Zh,heldFrontend:null,...de.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1})),!1)}finally{sn()}if(Xe.current!==W||Ce())return!1;if(Ye(A.current.transcript)!==le){if(!A.current.hydrated)continue;return!1}C.current.refused=!1;const nt=$.entries[0];It+=$.entries.length,Me?.($.entries.length),ii(ce.current,$.entries),Fr(x.current,$.entries),O(de=>{if(Ye(de.transcript)!==le)return de;const dt=Yn(de.transcript,$,{authoritative:!0,orderRead:be,peerSource:R()}),cn=Js($.entries,E),js=new Set(de.labelPending);for(const Ju of cn)js.delete(Ju);return{...de,hydrated:de.hydrated||$.entries.length>0||!xr,labelPending:js.size?js:Ht,labelMarked:cv(de.labelMarked,cn),transcript:dt}}),e&&He===void 0&&ze.getState().resolveHeldFromServer(e,$.entries,!$.cursor_missing);const Ft=lt();for(const de of Js($.entries,E))tt.add(de),E.add(de);if(b_($.entries)&&(on=!0),De){const de=w_($.entries,E);for(const dt of de)w.add(dt),E.add(dt);for(const[dt,cn]of y_($.entries,de))fe.set(dt,cn);for(const dt of[...w])tt.has(dt)&&w.delete(dt);w.size>0&&ve--<=0&&w.clear()}et=et||z.size===0||$.entries.some(de=>z.has(rt(de))||Ge.has(de.id)),xt=xt||$.entries.some(de=>Y.has(rt(de)));for(const de of $.entries)Ge.add(de.id);for(const de of $.entries)Be.keys.add(rt(de));nt&&(Be.oldest=nt),Be.hasMore=$.has_more,Be.joined=et,Be.reachedHeld=xt;const an=lt()+w.size;De&<()<Ft&&(C.current.depth=Math.min(wo,Math.max(C.current.depth,It)));let oa=!1;if(De){const de=Tr();oa=__($.entries,de,ie.starts,Ps(),new Set(de.filter(cn=>ie.waiting.has(cn))))||on}if(S_(et&&xt,oa?0:an)||!nt||!$.has_more)return!1;He=nt.id,Z=an>0?mc(an):Ci}return!1},na=()=>{if(we&&cancelAnimationFrame(we),$e&&clearTimeout($e),we=0,$e=0,Xe.current!==T)return;const W=U.current;if(U.current=[],W.length===0)return;const z=new Set,Y=new Map;for(const E of ce.current)A.current.transcript.index.has(E)||ce.current.delete(E);for(const E of x.current)A.current.transcript.index.has(E)||x.current.delete(E);for(const E of A.current.transcript.records)_o(E)&&!ce.current.has(E.id)&&(z.add(E.id),Y.set(E.id,x.current.has(E.id)?E.ts:null));let ee=null;for(const E of W){if(E.type!=="snapshot")continue;const w=E.payload.history,fe=w.entries[0];if(!fe||!w.has_more)continue;const ve=Math.round((fe.ts??0)*1e3);ve>0&&(!ee||ve<ee.ts)&&(ee={id:fe.id,ts:ve})}ov(W);const ie=E=>{const w=E.payload.history.entries,fe=w.at(-1);if(!fe)return!1;if(Lv(E.payload)){if(z.size===0)return!0;const ve=new Set;for(const De of w)ve.add(rt(De));return w.some(De=>z.has(rt(De)))?!0:fm(E.payload.history,Y,ve)}return fe.id===E.payload.frontend.snapshot.history_cursor?!1:z.has(rt(fe))},q=E=>E!=null&&V.current.has(E);let Be=!1;const Me=W.some(E=>E.type==="attention"?!q(E.payload.anchor_id):E.type==="snapshot"&&!ie(E)),Ie=A.current.cold&&!A.current.hydrated&&W.some(E=>E.type==="snapshot"||E.type==="frontend.replace"||E.type==="frontend.update"?E.payload.cold===!1:!1),Ce=new Set(A.current.transcript.argsByCall.keys()),Ge=[],He=new Set;for(const E of W){if(E.type!=="snapshot")continue;const w=se(E,A.current.transcript);w||Fr(x.current,E.payload.history.entries);for(const fe of E.payload.history.entries){w||He.add(rt(fe));const ve=fe.payload?.tool_calls;if(Array.isArray(ve))for(const De of ve)De&&typeof De.id=="string"&&Ce.add(De.id)}for(const fe of E.payload.frontend.snapshot.live_events??[]){const ve=fe.message;!w&&typeof ve?.id=="string"&&He.add(ve.id)}Ge.push(...E.payload.frontend.snapshot.live_events??[])}const It=W.some(E=>E.type==="event"&&Tc.has(String(E.payload.type??""))),We=hc(C.current.attempts,pc(Ge,Ce),Ce,Cc),et=It?hc(C.current.attempts,[...C.current.attempts.keys(),...C.current.settled],Ce,Cc):[],xt=[];for(const E of W){if(E.type!=="event")continue;const w=E.payload;String(w.type??"")==="tool_execution_end"&&String(w.tool_call_id??"")&&xt.push(w)}const on=[];for(const E of xt){const w=String(E.tool_call_id??"");Ce.has(w)||C.current.settled.has(w)||on.push(w)}for(const E of on)C.current.settled.add(E);for(;C.current.settled.size>xc;){const E=C.current.settled.values().next().value;if(E===void 0)break;C.current.settled.delete(E)}for(const[E,w]of fc(xt))C.current.starts.set(E,w);for(;C.current.starts.size>Pc;){const E=C.current.starts.keys().next().value;if(E===void 0)break;C.current.starts.delete(E)}const xr=C.current.settleRows<_v?on:[],tt=[...new Set([...We,...et,...xr])],lt=tt.filter(E=>!C.current.painted.has(E));if(Ge.length>0){C.current.order=pc(Ge,new Set);for(const[E,w]of fc(Ge))C.current.starts.set(E,w);for(;C.current.starts.size>Pc;){const E=C.current.starts.keys().next().value;if(E===void 0)break;C.current.starts.delete(E)}for(const E of m_(Ge))C.current.waiting.add(E);for(const E of k_(Ge))C.current.waiting.delete(E);for(;C.current.waiting.size>kv;){const E=C.current.waiting.values().next().value;if(E===void 0)break;C.current.waiting.delete(E)}}for(const E of[...C.current.attempts.keys()])Ce.has(E)&&C.current.attempts.delete(E);for(Te([...We,...et]);C.current.attempts.size>xc;){const E=C.current.attempts.keys().next().value;if(E===void 0)break;C.current.attempts.delete(E)}if(performance.mark("lop:transcript:flush:start"),O(E=>{let w={...E},fe=w.frontend!==null;Be=!1;let ve=null;const De=Date.now();for(const Z of W){if(Z.type==="heartbeat")continue;if(Z.type==="gap"){w={...w,frontend:null,heldFrontend:w.frontend??w.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:gc(w.transcript)},fe=!1;continue}const jn=je.current;if((Z.type==="open"||"seq"in Z)&&(je.current={epoch:Z.epoch,seq:Z.seq},w={...w,receipt:je.current}),Z.type==="open"){if(w={...w,subscriptionId:Z.payload.subscription_id},Z.payload.gap){const $=w.frontend??w.heldFrontend;w={...w,frontend:null,heldFrontend:$,history:null,transcript:gc(w.transcript)},$&&w.status==="live"&&(w={...w,status:"reconnecting"}),fe=!1}continue}if(!fe){if(Z.type==="event"&&(ve=Ti(ve??w.transcript,Z.payload,De,{frame:{epoch:Z.epoch,seq:Z.seq}})),Z.type==="snapshot"){const $=K.get(Z),be=se(Z,w.transcript);be&&(Be=!0);const le=Z.payload,nt=!le.history.cursor_missing&&!be;let Ft=ve??w.transcript;nt&&(performance.mark("lop:open:history:start"),Ft=Yn(Ft,le.history,{authoritative:!0,orderRead:$,peerSource:R()}),performance.mark("lop:open:history:end"),performance.measure("lop:open:history","lop:open:history:start","lop:open:history:end"),ii(ce.current,le.history.entries),Fr(x.current,le.history.entries)),e&&ze.getState().resolveHeldFromServer(e,le.history.entries,nt),performance.mark("lop:open:seed:start"),Ft=h_(Ft,le.frontend.snapshot,De,{epoch:Z.epoch,seq:Z.seq}),performance.mark("lop:open:seed:end"),performance.measure("lop:open:seed","lop:open:seed:start","lop:open:seed:end");const an=Ec(w.frontend??w.heldFrontend,le.frontend.snapshot,le.cold===!0||le.attaching===!0);w={...w,contextCarried:Object.keys(an).length>0,subagentPulses:sv(le.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...le.frontend.snapshot,...an,attention:mn(w.frontend?.attention,le.frontend.snapshot.attention,e)},history:be?w.history:le.history,cold:le.cold,ownerEpoch:le.frontend.epoch,failure:null,hydrated:w.hydrated||nt&&le.history.entries.length>0,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloadFailed:!1,liveUpdatesReloading:!1,transcript:Ft},fe=!0,ve=null}continue}if(Z.type==="attention"){w.frontend&&(w={...w,frontend:{...w.frontend,attention:mn(w.frontend.attention,Z.payload,e)}});continue}if(Z.type==="frontend.update"){const $=Z.payload,be=$.changes??{};if(($.degraded===!0||$.paused===!0)&&(w={...w,liveUpdatesPaused:!0,liveUpdatesNotice:"update",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}),!w.frontend)continue;const le=$.epoch!==w.ownerEpoch&&be.epoch===$.epoch,nt=$.changes!==void 0&&be.epoch===$.epoch;(le||$.epoch===w.ownerEpoch&&(w.frontend.sequence<$.sequence||w.frontend.sequence===$.sequence&&nt))&&(w={...w,contextCarried:!1,ownerEpoch:le?$.epoch:w.ownerEpoch,frontend:{...w.frontend,...be,...be.jobs==null&&$.job_deltas?{jobs:cm(w.frontend.jobs??[],$.job_deltas)}:{},attention:mn(w.frontend.attention,be.attention,e),sequence:$.sequence},...typeof $.cold=="boolean"?{cold:$.cold}:{}},nt&&w.liveUpdatesNotice==="update"&&w.liveUpdatesPaused&&(w={...w,liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}));continue}if(Z.type==="frontend.replace"){if(w.frontend&&Hh(jn,e,Z)){const $=Z.payload.frontend,be=Ec(w.frontend,$.snapshot,Z.payload.cold===!0);w={...w,contextCarried:Object.keys(be).length>0,frontend:{...$.snapshot,...be,attention:mn(w.frontend.attention,$.snapshot.attention,e)},ownerEpoch:$.epoch,cold:Z.payload.cold,...w.liveUpdatesPaused?{liveUpdatesPaused:!1,liveUpdatesNotice:"none",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1}:{}}}continue}if(Z.type==="event"){const $=String(Z.payload.type??"");if(Z.payload.action==="reload"){w={...w,liveUpdatesPaused:!0,liveUpdatesNotice:"event",liveUpdatesReloading:!1,liveUpdatesReloadFailed:!1};continue}lv.has($)&&(w={...w,terminal:$}),Tc.has($)&&(w={...w,turnsCompleted:w.turnsCompleted+1});const be=Ti(w.transcript,Z.payload,De,{frame:{epoch:Z.epoch,seq:Z.seq},userStoppedAt:e?ze.getState().stoppedTurns[e]??null:null,queuedAskEngine:Td(w.frontend)});be!==w.transcript&&(w={...w,transcript:be});const le=iv(w.subagentPulses,Z.payload);le!==w.subagentPulses&&(w={...w,subagentPulses:le})}}if(!fe&&ve){for(const Z of ve.index.keys())w.transcript.index.has(Z)||ce.current.add(Z);w={...w,transcript:ve}}if(performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),V.current=w.transcript.index,!av(W))return E;if(lt.length>0){const Z=new Set(w.labelPending);for(const jn of lt)Z.add(jn);w={...w,labelPending:Z}}return w.frontend!==null&&w.frontend!==w.heldFrontend&&(w={...w,heldFrontend:w.frontend}),w}),lt.length>0){for(const E of lt)C.current.painted.add(E);for(;C.current.painted.size>Sv;){const E=C.current.painted.values().next().value;if(E===void 0)break;C.current.painted.delete(E)}}const Tr=Me||Be,Ps=xr.length>0&&We.length===0&&et.length===0&&!Tr&&!Ie;if(Tr||tt.length>0||Ie){const E=new Set(tt),w=C.current.order;Ir(T,He,tt.length>0?{targets:E,order:w,starts:C.current.starts,waiting:C.current.waiting,every:new Set([...w,...E]),found:new Set(Js(W.flatMap(fe=>fe.type==="snapshot"?fe.payload.history.entries:[]),new Set(w))),pending:lt}:Oc,1,Ps?fe=>{C.current.settleRows+=fe}:void 0,z,ee)}},On=()=>{const W=pe;if(pe=null,f.current=null,p.current+=1,h.current&&(window.clearTimeout(h.current),h.current=0),g.current+=1,!!W){H=!0;try{W()}finally{H=!1}}},Pn=()=>{const W=wi(A.current.transcript);Se(),he=window.setTimeout(()=>{he=0,Xe.current===T&&(On(),O(Y=>({...Y,subscriptionId:null,status:"unavailable",failure:za(Zn.ended),...Y.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null})),!Ee&&(Ee=!0,oe=window.setTimeout(()=>{oe=0,Xe.current===T&&sa()},pv)))},fv);const z=_();pe=am({sessionId:e,epoch:xn.current.epoch,afterSeq:xn.current.afterSeq,openFrame:l.current,...c.current?{journalOrder:a,orderIds:ut(A.current.transcript).slice(0,512),...z?{peerJournalSource:!0}:{}}:{}},Y=>{if(Xe.current===T){if(Y.kind==="error"||Y.kind==="end"){if(H)return;if(Se(),On(),Y.kind==="error"&&Y.status===404){if(!n){e&&ze.getState().retireDraftWarm(e),O(q=>({...q,subscriptionId:null}));return}e&&(z_(e),Q_(e),ev(e),ze.getState().retireDraftsForSession(e)),O(q=>({...q,subscriptionId:null,status:"unavailable",missing:!0,failure:null,...q.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}const ee=Y.kind==="error"?Y.detail??"The event stream failed.":"The event stream closed unexpectedly.";if(O(q=>({...q,subscriptionId:null})),ue>=uv){O(q=>({...q,status:"unavailable",failure:za(ee),...q.liveUpdatesReloading?{liveUpdatesReloadFailed:!0}:{},liveUpdatesReloading:!1,heldFrontend:null}));return}ue+=1;const ie=je.current;ie&&(xn.current={epoch:ie.epoch,afterSeq:ie.seq}),O(q=>q.status==="unavailable"&&ue>1?q:{...q,status:"reconnecting",failure:null}),me=window.setTimeout(()=>{me=0,Xe.current===T&&Pn()},Ic(ue));return}if(Y.data!==void 0)try{const ee=Y.data,ie=ee.length>=yv;ie&&performance.mark("lop:open:parse:start");const q=JSON.parse(ee);q.type==="snapshot"&&K.set(q,W),ie&&(performance.mark("lop:open:parse:end"),performance.measure("lop:open:parse","lop:open:parse:start","lop:open:parse:end")),q.type==="snapshot"&&(ue=0,Se(),Ee=!1),U.current.push(q),we||(we=requestAnimationFrame(na)),$e||($e=window.setTimeout(na,gv))}catch{}}}),f.current={sessionId:e,peer:z},p.current+=1},ra=()=>{me!==0&&(window.clearTimeout(me),me=0),xn.current={},je.current=null,On(),Pn()},sa=()=>{ue=0,oe&&(window.clearTimeout(oe),oe=0),me&&(window.clearTimeout(me),me=0),D&&(window.clearTimeout(D),D=0),O(W=>({...W,failure:null,status:W.status==="unavailable"?"connecting":W.status,transcript:$r(W.transcript,!1)})),A.current.hydrated||Ir(T,new Set(A.current.transcript.index.keys())),!pe&&Pn()};Pn(),Is.current=sa,xs.current=()=>{A.current.liveUpdatesReloading||(O(W=>({...W,liveUpdatesReloading:!0,liveUpdatesReloadFailed:!1})),ue=0,me&&(window.clearTimeout(me),me=0),oe&&(window.clearTimeout(oe),oe=0),ra())},Ts.current=()=>{!A.current.hydrated&&Tn.current===0&&Ir(T,new Set(A.current.transcript.index.keys()))};const Yu=Ev(e,ra),ia=()=>{if(!t||!e||m.current===e)return;const W=f.current;W===null||W.sessionId!==e||W.peer||_()&&(m.current=e,On(),Pn())};y.current=ia;const Qu=ze.subscribe(()=>{ia()});return()=>{Xe.current+=1,Is.current=null,Ts.current=null,xs.current=null,y.current=null,Qu(),h.current&&(window.clearTimeout(h.current),h.current=0),Yu(),On(),we&&cancelAnimationFrame(we),$e&&clearTimeout($e),me&&clearTimeout(me),D&&clearTimeout(D),qe.current&&(window.clearTimeout(qe.current),qe.current=0),yt.current&&(window.clearTimeout(yt.current),yt.current=0),oe&&window.clearTimeout(oe),Se(),U.current=[]}},[O,e,t,n,a,_,b,R]),v.useEffect(()=>{!e||!t||y.current?.()},[e,t,d]),v.useEffect(()=>{xn.current={},je.current=null,V.current=st.index;const T=Mv(S.current,e,n);S.current=e;const K=e?Fd(e):null;V.current=T?A.current.transcript.index:(K?.transcript??st).index;const se=new Set(T?ce.current:[]);for(const H of K?.replayBorn??[])se.add(H);const pe=T?A.current.transcript.index:(K?.transcript??st).index;for(const H of se)pe.has(H)||se.delete(H);ce.current=se,T||(x.current=new Set),O(H=>({...H,frontend:null,heldFrontend:T?H.heldFrontend:null,contextCarried:T?H.contextCarried:!1,pendingModel:null,history:null,terminal:null,turnsCompleted:T?H.turnsCompleted:0,transcript:T?H.transcript:K?.transcript??st,stale:T?H.stale:K!==null,missing:T?H.missing:!1,status:"connecting",subagentPulses:{},labelPending:K?.owedLabels??Ht,labelMarked:K?.markLabels??Hn,labelHoldLate:!1,hydrated:!1,loadingOlder:!1,historyReadPending:!1,olderFailed:!1})),C.current=jc(e)},[e,n]),v.useEffect(()=>{if(e)return()=>{const T=A.current.transcript;T.records.length>0&&W_(e,{transcript:T,owedLabels:new Set([...A.current.labelPending].filter(K=>si(C.current,A.current.transcript.argsByCall,K,ri(A.current)))),markLabels:new Set(A.current.labelMarked),replayBorn:new Set(ce.current)});for(const K of re.current)C.current.inFlight.delete(K);re.current.clear()}},[e]);const qe=v.useRef(0);v.useEffect(()=>{if(M.labelPending.size===0&&M.labelMarked.size===0){qe.current&&(window.clearTimeout(qe.current),qe.current=0);return}if(qe.current)return;const T=()=>{qe.current=0;const K=A.current.labelPending,se=A.current.labelMarked;if(K.size===0&&se.size===0)return;const pe=C.current;for(const H of K)if(pe.inFlight.has(H)){qe.current=window.setTimeout(T,ni);return}for(const H of se)if(pe.inFlight.has(H)){qe.current=window.setTimeout(T,ni);return}O(H=>H.labelPending.size===0&&H.labelMarked.size===0?H:{...H,labelPending:Ht,labelMarked:Hn})};qe.current=window.setTimeout(T,ni)},[O,M.labelPending,M.labelMarked]);const yt=v.useRef(0);v.useEffect(()=>{if(M.labelPending.size===0){yt.current&&(window.clearTimeout(yt.current),yt.current=0),O(T=>T.labelHoldLate?{...T,labelHoldLate:!1}:T);return}M.labelHoldLate||yt.current||(yt.current=window.setTimeout(()=>{yt.current=0,O(T=>T.labelPending.size===0||T.labelHoldLate?T:{...T,labelHoldLate:!0})},bv))},[O,M.labelPending,M.labelHoldLate]);const Et=v.useRef(e);Et.current=e;const Cn=v.useRef({id:e,epoch:0});Cn.current.id!==e&&(Cn.current={id:e,epoch:Cn.current.epoch+1});const Cs=v.useRef(null);Cs.current===null&&(Cs.current=tv());const As=v.useRef(!1),An=v.useRef(null),[Zo,zu]=v.useState(0);v.useEffect(()=>{const T=M.transcript,K=ut(T);if(!e||!a||!T.orderNeedsReconcile&&(!T.journalGeneration||K.length===0)||As.current)return;const se=D=>({fields:JSON.stringify([Zo,e,D.viewEpoch,Ye(D),D.orderNeedsReconcile,D.orderWantedGeneration,ut(D)]),demand:D.orderDemand}),pe=se(T);if(An.current?.fields===pe.fields&&An.current.demand===pe.demand)return;An.current=pe;const H=e,we=T.viewEpoch;As.current=!0;let $e=null,ue=T;const me=D=>{if(!D.peer||Et.current!==H||A.current.transcript.viewEpoch!==we||p.current!==D.streamEpoch)return;const he=D.kind==="authority"?D.frame.payload.history:D.page,oe=he.journal_order_state;if(oe==="ready"){h.current&&(window.clearTimeout(h.current),h.current=0),O(Se=>{const Te=$r(Se.transcript,!1);return Te===Se.transcript?Se:{...Se,transcript:Te}});return}if(oe==="unavailable"){if(h.current&&(window.clearTimeout(h.current),h.current=0),he.reconcile===!0)return;O(Se=>{const Te=$r(Se.transcript,!0);return Te===Se.transcript?Se:{...Se,transcript:Te}});return}if(oe!=="building")return;h.current&&(window.clearTimeout(h.current),h.current=0);const Ee=++g.current;h.current=window.setTimeout(()=>{h.current=0,g.current===Ee&&Et.current===H&&A.current.transcript.viewEpoch===we&&p.current===D.streamEpoch&&O(Se=>{const Te=$r(Se.transcript,!0);return Te===Se.transcript?Se:{...Se,transcript:Te}})},hv)};dm({getTranscript:()=>A.current.transcript,isCurrent:()=>Et.current===H&&A.current.transcript.viewEpoch===we,sweep:(D,he)=>{if(!b())return;if(D.orderNeedsReconcile===!0)return{kind:"authority",path:`/v1/desktop/sessions/${H}`,query:new URLSearchParams({journal_order:"1",peer_journal_source:"1"})};const oe=D.journalGeneration;if(typeof oe!="string"||oe.length===0)return{kind:"none",path:`/v1/desktop/sessions/${H}/history`,query:new URLSearchParams};if(Nl(D,he?.("lookup")).length>0){const Te=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"metadata",expected_journal_generation:oe});return{kind:"lookup",path:`/v1/desktop/sessions/${H}/history`,query:Te}}if(io(D).length>0){const Te=new URLSearchParams({limit:"100",journal_order:"1",peer_journal_source:"1",source_read:"payload",expected_journal_generation:oe});return{kind:"payload",path:`/v1/desktop/sessions/${H}/history`,query:Te}}return{kind:"none",path:`/v1/desktop/sessions/${H}/history`,query:new URLSearchParams}},read:async(D,he)=>{ue=A.current.transcript,An.current=se(ue);const oe=b(),Ee=p.current;if(he==="lookup"||he==="payload"){const Te=A.current.transcript.journalGeneration,sn=await xe({op:"sessions.history",sessionId:H,limit:100,journalOrder:!0,orderIds:D,peerJournalSource:!0,sourceRead:he==="payload"?"payload":"metadata",...typeof Te=="string"&&Te.length>0?{expectedJournalGeneration:Te}:{}});return he==="payload"?{kind:"payload",page:sn,peer:oe,streamEpoch:Ee}:{kind:"lookup",page:sn,peer:oe,streamEpoch:Ee}}return{kind:"authority",frame:await xe({op:"sessions.get",sessionId:H,journalOrder:!0,orderIds:D,...oe?{peerJournalSource:!0}:{}}),peer:oe,streamEpoch:Ee}},page:D=>D.kind==="authority"?D.frame.payload.history:D.page,lookupPath:`/v1/desktop/sessions/${H}`,commit:(D,he,oe)=>{D.peer&&p.current!==D.streamEpoch||(O(Ee=>Et.current!==H||Ye(Ee.transcript)!==he||Ee.transcript.viewEpoch!==we?Ee:{...Ee,transcript:D.kind==="authority"?D.peer?uc(Ee.transcript,D.frame.payload.history,{authoritative:!0,orderRead:oe}):a_(Ee.transcript,D.frame.payload.history,oe):D.kind==="payload"?c_(Ee.transcript,D.page,oe,he):uc(Ee.transcript,D.page,{authoritative:!1})}),me(D))}}).then(D=>{$e=D.kind==="complete"?D.transcript:null}).catch(D=>{console.warn("[canonical] source-order reconcile refused",D)}).finally(()=>{As.current=!1;const D=A.current.transcript,he=$e??ue;$e&&Et.current===H&&D.viewEpoch===we&&!D.orderNeedsReconcile&&(An.current=se(he)),(Et.current!==H||D.viewEpoch!==we||Ye(D)!==Ye(he)||D.orderWantedGeneration!==he.orderWantedGeneration||D.orderNeedsReconcile!==he.orderNeedsReconcile||D.orderDemand!==he.orderDemand||JSON.stringify(ut(D))!==JSON.stringify(ut(he)))&&zu(oe=>oe+1)})},[O,e,a,b,M.transcript,Zo]);const Er=v.useCallback(async()=>{const T=Cs.current;if(!e||!T)return{kind:"nothing-to-load"};const K=e,se=Cn.current.epoch,pe=()=>Cn.current.epoch===se,H=A.current.transcript.viewEpoch,we=()=>A.current.transcript.viewEpoch===H,$e=await T.load(`${K}#${se}`,{getTranscript:()=>A.current.transcript,readPage:ue=>xe({op:"sessions.history",sessionId:K,beforeId:ue,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}}),isCurrent:()=>pe()&&we(),commit:ue=>O(me=>{const D=ue(me.transcript);return D===me.transcript?me:{...me,transcript:D}}).transcript,setLoading:ue=>{pe()&&O(me=>me.loadingOlder===ue?me:{...me,loadingOlder:ue})},peerSource:R});return pe()&&($e.kind==="failed"?O(ue=>ue.olderFailed?ue:{...ue,olderFailed:!0}):$e.kind==="applied"&&O(ue=>ue.olderFailed?{...ue,olderFailed:!1}:ue)),$e},[O,e,b,R]),Vo=v.useCallback(async()=>(await Er()).kind==="applied",[Er]),Os=v.useRef(!1),Ko=v.useCallback(async(T,K)=>{if(!e||Os.current)return!1;const se=e;Os.current=!0;const pe=Ye(A.current.transcript);try{const H=await xe({op:"sessions.history",sessionId:se,limit:100,openFrame:l.current,...c.current?{journalOrder:!0,orderIds:ut(A.current.transcript).slice(0,512),...b()?{peerJournalSource:!0}:{}}:{}});return Et.current!==se||Ye(A.current.transcript)!==pe||A.current.transcript.viewEpoch!==K?!1:(O(we=>Ye(we.transcript)!==pe?we:{...we,transcript:Yn(we.transcript,H,{keepPaging:!0,peerSource:R()})}),ii(ce.current,H.entries),Fr(x.current,H.entries),O_(H.entries,T))}catch{return!1}finally{Os.current=!1}},[O,e,b,R]);v.useEffect(()=>r?Pv(r,K=>{O(se=>{const pe=K(se.transcript);return pe===se.transcript?se:{...se,transcript:pe}})}):void 0,[O,r]),v.useEffect(()=>{r&&Ov(r,M.transcript)},[r,M.transcript]);const Yo=v.useCallback(()=>{O(T=>({...T,transcript:E_(T.transcript),olderFailed:!1,heldFrontend:null}))},[O]),Qo=v.useCallback(()=>{Is.current?.()},[]),Jo=v.useCallback(()=>{xs.current?.()},[]),Xo=v.useCallback(()=>{Ts.current?.()},[]),qo=v.useCallback((T,K="info")=>{O(se=>({...se,transcript:T_(se.transcript,T,K)}))},[O]),ea=v.useCallback(T=>{O(K=>({...K,pendingModel:T}))},[O]),ta=v.useCallback(()=>{O(T=>T.pendingModel===null?T:{...T,pendingModel:null})},[O]);return v.useEffect(()=>{const T=M.pendingModel;if(!T)return;const K=Xs(T);if(!K)return;const se=M.frontend;(Xs(se?.selected_model)===K||Xs(se?.effective_model)===K)&&O(pe=>({...pe,pendingModel:null}))},[O,M.frontend,M.pendingModel]),v.useEffect(()=>{if(!M.pendingModel)return;const T=window.setTimeout(()=>O(K=>({...K,pendingModel:null})),dv);return()=>window.clearTimeout(T)},[O,M.pendingModel]),v.useMemo(()=>({...M,awaitingHydration:t&&!!e&&n&&!M.hydrated,loadOlder:Vo,loadOlderDetailed:Er,refreshTail:Ko,clearView:Yo,addNote:qo,paintPendingModel:ea,clearPendingModel:ta,retry:Qo,rehydrate:Xo,reloadFromHistory:Jo}),[M,t,e,n,Vo,Er,Ko,Yo,qo,ea,ta,Qo,Xo,Jo])}function ys(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
35
35
|
|
|
36
36
|
`)?e:`${t}
|
|
37
37
|
|
|
38
|
-
${e}`}const oi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Zr(e,t,n){const r=[...e.attachments??[]],s=[],i=[],a=new Set;for(const p of t.attachments){const h=r.find(m=>m.path===p&&!a.has(m.id));if(h){a.add(h.id),i.push(h.id);continue}const g={id:n(),path:p};s.push(g),i.push(g.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(h=>h.id===p.id)),d=t.text,u=[...s,...r],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:ys(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(h=>h.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function $v(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function Uv(e){return{text:ys(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Fv(e,t){if(!e||!t)return!1;const n=Uv(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((i,a)=>i.id===t.chipIds[a])&&s.length===t.replyIds.length&&s.every((i,a)=>i.id===t.replyIds[a])}function Bv(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?Zr(s,s.inFlight,t):s;return n}function Gv(e,t){const n=t.text,r=ys(e.currentInput??"",e.pendingText??"");let s=r,i="overlap";n===""?i="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),i="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Ne=vr()(hs((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...i,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(i=>i.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...i,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(i=>i.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!$v(i,r)?void 0:i.lateDelivered,currentInput:r,unredactedChars:r?s:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages[s.submittedMessages.length-1],a=r&&r!==i?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages;let a=null;typeof r=="number"&&i.length>0&&(a=Math.max(0,Math.min(r,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...s}=t().inputByConversation;e({inputByConversation:s})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,s=!0)=>{const i=t().inputByConversation[n]??oi,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=i.currentInput===r.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=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?i.unredactedChars:0,volatileText:r.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const i of n){const a=r[i];!a||!a.inFlight&&!a.returned||(r[i]={...a,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},i=s[n],a=i?.inFlight??s[r]?.inFlight;let c=s[r]??oi;n!==r&&i&&(c=Zr(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),a&&(c=Zr(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=ys(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:s,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),s},returnPayload:(n,r)=>{const s=t().inputByConversation[n]??oi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Zr(s,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const s=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?Fv(r,r.returned):s(r),c=r.returned?Gv(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!s(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:i&&r.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&s(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,unredactedChars:s.unredactedChars??0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:Bv(e?.inputByConversation)})}));function X(e){return typeof e=="string"?e.trim():""}function fn(e){const t=X(e);return t||null}function Ut(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Wn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function zd(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Qt(e,t){return typeof e=="boolean"?e:t}function Mi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function En(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null);if(typeof e=="object"&&e!==null){const t=e.peers;if(Array.isArray(t))return En(t)}return[]}function Hv(e){if(!Pt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:zd(e.attempts),last_frame_at:Ut(e.last_frame_at),next_retry_at:Ut(e.next_retry_at),last_error:X(e.last_error)}}function Pt(e){return typeof e=="object"&&e!==null}const Wv=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function zv(e,t){const n=X(e);return Wv.includes(n)?n:t?"reachable":"unreachable_legacy"}const Zv=["running","not_listening","unknown"];function Vv(e){const t=X(e);return Zv.includes(t)?t:void 0}function Kv(e){if(Array.isArray(e))return e.filter(Pt).map(t=>({endpoint:X(t.endpoint),connected:t.connected===!0,detail:X(t.detail),latency_ms:Ut(t.latency_ms)})).filter(t=>t.endpoint!=="")}function rE(e){const t=new Set,n=[];for(const a of En(e)){const c=X(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=Vv(a.remote_relay),d=Kv(a.attempts),u=a.reachable?void 0:Hv(a.redial);n.push({device_id:c,name:X(a.name),reachable:a.reachable,link_state:zv(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:fn(a.unreachable_reason??a.reason),last_seen_at:Ut(a.last_seen_at),session_count:Wn(a.session_count),rtt_ms:Ut(a.rtt_ms)})}const r=Pt(e)?e:{},s=X(r.self_device_id),i=Mi(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...i.length?{degraded:i}:{}}}function Yv(e){const t=X(e.device_id);return t?{device_id:t,name:X(e.name),role:X(e.role),capabilities:Mi(e.capabilities),active:Qt(e.active,!0),suspect:Qt(e.suspect,!1),endpoints:Mi(e.endpoints),last_seen_at:Ut(e.last_seen_at),reachable:Qt(e.reachable,!0),reason:X(e.reason??e.unreachable_reason),scope:X(e.scope)}:null}function Qv(e){const t=X(e.network_id);return t?{network_id:t,name:X(e.name),epoch:zd(e.epoch),trust:X(e.trust),members:En(e.members).map(Yv).filter(n=>n!==null)}:null}function sE(e){const t=Pt(e)?e:{},n=X(t.self_device_id);return{networks:En(t.networks).map(Qv).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function Jv(e){return e.live_state.trim().toLowerCase()==="busy"}function iE(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of En(r)){const i=X(s.id);if(!i||n.has(i))continue;const a=s.locality==="remote"?"remote":X(s.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Pt(s.status)?{code:X(s.status.code),label:X(s.status.label)}:null,l=Pt(s.binding)?{agent:fn(s.binding.agent),team:fn(s.binding.team)}:null,d=Pt(s.opened_by)?{agent:fn(s.opened_by.agent),label:fn(s.opened_by.label),session:fn(s.opened_by.session)}:null;t.push({id:i,name:X(s.name),mtime:Ut(s.mtime)??0,locality:a,owner_device:X(s.owner_device),owner_device_name:X(s.owner_device_name),reachable:Qt(s.reachable,!0),unreachable_reason:X(s.unreachable_reason),live_state:X(s.live_state),archived:Qt(s.archived,!1),created_at:Ut(s.created_at),pinned:Qt(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Wn(s.waiting_on),jobs_running:Wn(s.jobs_running),subagents_running:Wn(s.subagents_running),subagents_queued:Wn(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function oE(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function aE(e){if(!Pt(e))return null;const t=X(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=X(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:X(e.owner_device),source_retired:Qt(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:En(e.phases).map(s=>({phase:X(s.phase),peer:X(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const Xv=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function cE(e){const t=e,n=X(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:X(t?.message)||"the move was refused",status:r,unconfirmed:r===503||Xv.has(n)}}function lE(e){const t=X(e.name);return t||ae("ui.mesh.mesh_types.device_suffix",{suffix:X(e.device_id).slice(-6)})}function dE(e){const t=X(e.name);return t||ae("ui.mesh.mesh_types.network_suffix",{suffix:X(e.network_id).slice(-6)})}const qv=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function eb(e){const t=e.trim();return t!==""&&qv.includes(t)}function Zd(e){return e.state==="self"?"self":e.reachable?"reached":e.state==="relay_down"?"relay-down":e.state==="handshake_refused"?"handshake-refused":e.linkState==="address_unreachable"?"address-unreachable":e.linkState==="no_endpoint"?"no-endpoint":e.linkState==="not_a_member"?"not-a-member":e.linkState==="not_attempted"||eb(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const uE=()=>ae("ui.mesh.mesh_graph.identity_suspect");function Vd(e){switch(e){case"self":return ae("ui.mesh.mesh_drop.this_device");case"reached":return ae("ui.mesh.mesh_reach.reached");case"relay-down":return ae("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return ae("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return ae("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return ae("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return ae("ui.mesh.mesh_reach.not_a_member");case"unanswered":return ae("ui.mesh.mesh_reach.no_answer");case"not-attempted":return ae("ui.mesh.mesh_reach.not_asked");default:return ae("ui.mesh.mesh_reach.unknown")}}function fE(e){const t=Zd(e),n=Vd(t);return e.reason?`${n} — ${e.reason}`:n}const pE={self:"text-accent",reached:"text-ink-muted","relay-down":"text-warning","handshake-refused":"text-warning","address-unreachable":"text-warning","no-endpoint":"text-ink-dim","not-a-member":"text-ink-dim",unanswered:"text-warning","not-attempted":"text-ink-dim",unknown:"text-ink-dim"},hE={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function mE(e){const t=e.trim();switch(t){case"ok":return ae("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return ae("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return ae("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return ae("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return ae("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?ae("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function gE(e){return e.reachable?"":e.remoteRelay==="not_listening"?ae("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?ae("ui.mesh.mesh_reach.peer_closed_handshake"):""}function yE(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>Jv(r))?"working":"idle",source:"derived"}}function tb(e,t){const n={...e};for(const[r,s]of Object.entries(t))(!n[r]||s.at>=n[r].at)&&(n[r]=s);return n}function nb(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=Zd({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",i=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===i&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:s,link_reconnecting:i,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function _E(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${ae("ui.chat.canonical.transcript.reconnecting")} · ${Di(n,t)}`:ae("ui.presence.link_down_last_seen",{age:Di(n,t)})}function Di(e,t){if(e===null)return ae("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?ae("ui.presence.just_now"):n<3600?ae("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?ae("ui.presence.hours_ago",{count:Math.floor(n/3600)}):ae("ui.presence.days_ago",{count:Math.floor(n/86400)})}function vE(e,t){if(e.link_reconnecting===!0)return ae("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return ae("ui.presence.link_down_compact",{age:Di(n,t)})}function rb(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>r));for(const[i,a]of Object.entries(t))(!s[i]||a.at>=s[i].at)&&(s[i]=a);return{facts:s,watermark:r,removed:Object.keys(e).filter(i=>!s[i])}}function bE(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Vd(e.peer_reach):null}function Ni(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const Br=(e,t)=>e instanceof ye?ro(e,t):e instanceof Error?e.message:t,_s="session_unvalidated",sb="This chat is not ready for messages yet, so the message was not sent. Sending works once it is ready.",cs="leading_slash_message",Kd="A message can't start with / — that is a command. Move it below your text, or send it on its own.";function ib(e,t){return e instanceof ye&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Yd="attachment_read_failed",Qd="store_out_of_space",Jd="store_unavailable";function Dc(e){return e===Qd||e===Jd}const ob="answer_not_sent",Xd="aside_not_answered",qd="aside_still_answering";function zn(e){return e===cs||e===Yd||e===Qd||e===Jd||e===ob||e===Xd||e===qd||e===_s||e===fs}function ab(e){return e instanceof ye&&e.status===409&&Ro(e)===void 0}function eu(e,t=!1){return db(e)||ab(e)&&!t?"not_sent":e instanceof ye&&e.status===404?"gone":"unknown"}function Ro(e){if(e instanceof ye||e instanceof $t)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Fe={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 wE(e){return e?Fe.gateLock:Fe.sendLock}const SE="Retry",kE="Clear";function cb(e,t,n=!1){const r=eu(e,n),s=t??Ro(e),i=ro(e,Fe.generic);return r==="gone"?{message:Fe.gone,retry:!1,code:s}:r==="not_sent"?s===fs?{message:Fe.busy,retry:!0,code:s}:s===kl?{message:Fe.retiring,retry:!0,code:s}:s===_s?{message:Fe.notReady,retry:!zn(s),code:s}:s===Xd?{message:Fe.asideNotAnswered,retry:!1,code:s}:s===qd?{message:Fe.asideStillAnswering,retry:!1,code:s}:s===cs?{message:Kd,retry:!1,code:s}:{message:i,retry:!1,code:s}:s===Je.transportFailed?{message:Fe.unreachable,retry:!0,code:s}:ps(s)?{message:to[s],retry:!1,code:s}:s===no?{message:Fe.unconfirmed,retry:!zn(s),code:s}:s===ah.runtimeUnreachable?{message:Fe.unconfirmed,retry:!0,code:s}:s?{message:i,retry:!zn(s),code:s}:{message:Fe.unconfirmed,retry:!zn(s),code:s}}function Li(e){return e.trim()}function RE(e,t){if(t.length===0)return Li(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
38
|
+
${e}`}const oi={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function Zr(e,t,n){const r=[...e.attachments??[]],s=[],i=[],a=new Set;for(const p of t.attachments){const h=r.find(m=>m.path===p&&!a.has(m.id));if(h){a.add(h.id),i.push(h.id);continue}const g={id:n(),path:p};s.push(g),i.push(g.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(h=>h.id===p.id)),d=t.text,u=[...s,...r],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:ys(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(h=>h.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function $v(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const r=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let s=0;s+r<=n.length;s++)if(t.includes(n.slice(s,s+r)))return!0;return!1}function Uv(e){return{text:ys(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Fv(e,t){if(!e||!t)return!1;const n=Uv(e),r=e.attachments??[],s=e.replies??[];return n.text.trim()===t.text.trim()&&r.length===t.chipIds.length&&r.every((i,a)=>i.id===t.chipIds[a])&&s.length===t.replyIds.length&&s.every((i,a)=>i.id===t.replyIds[a])}function Bv(e,t=()=>crypto.randomUUID()){const n={};for(const[r,s]of Object.entries(e??{}))n[r]=s.inFlight?Zr(s,s.inFlight,t):s;return n}function Gv(e,t){const n=t.text,r=ys(e.currentInput??"",e.pendingText??"");let s=r,i="overlap";n===""?i="draft-only":r.startsWith(n)&&(s=r.slice(n.length).replace(/^\n+/,""),i="draft-only");const a=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:s,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!a.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Ne=vr()(hs((e,t)=>({inputByConversation:{},addReply:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.replies)?s.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[...i,r]}}})},removeReply:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:s.replies.filter(i=>i.id!==r)}}})},clearReplies:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[]}}})},addAttachment:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(s.attachments)?s.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[...i,r]}}})},removeAttachment:(n,r)=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:s.attachments.filter(i=>i.id!==r)}}})},clearAttachments:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[]}}})},setCurrentInput:(n,r,s=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!$v(i,r)?void 0:i.lateDelivered,currentInput:r,unredactedChars:r?s:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages[s.submittedMessages.length-1],a=r&&r!==i?[...s.submittedMessages.slice(-19),r]:s.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:a}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=s.submittedMessages;let a=null;typeof r=="number"&&i.length>0&&(a=Math.max(0,Math.min(r,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:a}}})},resetCurrentHistoryIndex:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:r,...s}=t().inputByConversation;e({inputByConversation:s})},restoreRow:(n,r)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...r,textRevision:(r.textRevision??0)+1}}})},beginInFlight:(n,r,s=!0)=>{const i=t().inputByConversation[n]??oi,a=new Set(r.attachments.map(d=>d.id)),c=new Set(r.replies.map(d=>d.id)),l=i.currentInput===r.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=>!a.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:s?{text:r.text,attachments:r.attachments.map(d=>d.path),replies:[...r.replies],unredactedChars:l?i.unredactedChars:0,volatileText:r.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const r={...t().inputByConversation};let s=!1;for(const i of n){const a=r[i];!a||!a.inFlight&&!a.returned||(r[i]={...a,inFlight:void 0,returned:void 0},s=!0)}s&&e({inputByConversation:r})},returnInFlight:(n,r)=>{const s={...t().inputByConversation},i=s[n],a=i?.inFlight??s[r]?.inFlight;let c=s[r]??oi;n!==r&&i&&(c=Zr(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:s[r]?.returned},delete s[n]),a&&(c=Zr(c,a,()=>crypto.randomUUID())),!(!a&&n===r)&&(s[r]=c,e({inputByConversation:s}))},adoptReturnedText:n=>{const r=t().inputByConversation[n];if(r?.pendingText===void 0)return null;const s=ys(r.currentInput??"",r.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:s,pendingText:void 0,textRevision:(r.textRevision??0)+1}}}),s},returnPayload:(n,r)=>{const s=t().inputByConversation[n]??oi;s.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:Zr(s,r,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const r=t().inputByConversation[n];if(!r)return;const s=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=r.returned!==void 0||r.inFlight!==void 0,a=r.returned?Fv(r,r.returned):s(r),c=r.returned?Gv(r,r.returned):null,l={...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(r.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!s(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:r.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?r.returned?.text:void 0,textRevision:(r.textRevision??0)+1}:{...r,returned:void 0,inFlight:void 0,lateDelivered:i&&r.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?r.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:a||c!==null&&s(c.row)?l:u}})},dismissLateDelivery:n=>{const r=t().inputByConversation[n];r?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(r.textRevision??0)+1}}})},setComposerText:(n,r)=>{const s=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,unredactedChars:s.unredactedChars??0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let r=n;return r.inFlight?.volatileText&&(r={...r,inFlight:{...r.inFlight,text:""}}),r.returned?.volatileText&&(r={...r,returned:{...r.returned,text:""}}),r.volatilePendingText&&(r={...r,pendingText:void 0}),r.volatilePendingText&&(r={...r,lateDeliveredText:void 0}),[t,r]}))}),merge:(e,t)=>({...t,inputByConversation:Bv(e?.inputByConversation)})}));function X(e){return typeof e=="string"?e.trim():""}function fn(e){const t=X(e);return t||null}function Ut(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Wn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&Number.isInteger(e)?e:null}function zd(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.floor(e))}function Qt(e,t){return typeof e=="boolean"?e:t}function Mi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function En(e){if(Array.isArray(e))return e.filter(t=>typeof t=="object"&&t!==null);if(typeof e=="object"&&e!==null){const t=e.peers;if(Array.isArray(t))return En(t)}return[]}function Hv(e){if(!Pt(e))return;const t=e.state;if(!(t!=="reconnecting"&&t!=="down"))return{state:t,attempts:zd(e.attempts),last_frame_at:Ut(e.last_frame_at),next_retry_at:Ut(e.next_retry_at),last_error:X(e.last_error)}}function Pt(e){return typeof e=="object"&&e!==null}const Wv=["reachable","relay_down","address_unreachable","handshake_refused","not_attempted","no_endpoint","not_a_member"];function zv(e,t){const n=X(e);return Wv.includes(n)?n:t?"reachable":"unreachable_legacy"}const Zv=["running","not_listening","unknown"];function Vv(e){const t=X(e);return Zv.includes(t)?t:void 0}function Kv(e){if(Array.isArray(e))return e.filter(Pt).map(t=>({endpoint:X(t.endpoint),connected:t.connected===!0,detail:X(t.detail),latency_ms:Ut(t.latency_ms)})).filter(t=>t.endpoint!=="")}function sE(e){const t=new Set,n=[];for(const a of En(e)){const c=X(a.device_id);if(!c||t.has(c)||typeof a.reachable!="boolean")continue;t.add(c);const l=Vv(a.remote_relay),d=Kv(a.attempts),u=a.reachable?void 0:Hv(a.redial);n.push({device_id:c,name:X(a.name),reachable:a.reachable,link_state:zv(a.link_state,a.reachable),...l?{remote_relay:l}:{},...d?{attempts:d}:{},...u?{redial:u}:{},unreachable_reason:fn(a.unreachable_reason??a.reason),last_seen_at:Ut(a.last_seen_at),session_count:Wn(a.session_count),rtt_ms:Ut(a.rtt_ms)})}const r=Pt(e)?e:{},s=X(r.self_device_id),i=Mi(r.degraded);return{peers:n,...s?{self_device_id:s}:{},...i.length?{degraded:i}:{}}}function Yv(e){const t=X(e.device_id);return t?{device_id:t,name:X(e.name),role:X(e.role),capabilities:Mi(e.capabilities),active:Qt(e.active,!0),suspect:Qt(e.suspect,!1),endpoints:Mi(e.endpoints),last_seen_at:Ut(e.last_seen_at),reachable:Qt(e.reachable,!0),reason:X(e.reason??e.unreachable_reason),scope:X(e.scope)}:null}function Qv(e){const t=X(e.network_id);return t?{network_id:t,name:X(e.name),epoch:zd(e.epoch),trust:X(e.trust),members:En(e.members).map(Yv).filter(n=>n!==null)}:null}function iE(e){const t=Pt(e)?e:{},n=X(t.self_device_id);return{networks:En(t.networks).map(Qv).filter(r=>r!==null),...n?{self_device_id:n}:{}}}function Jv(e){return e.live_state.trim().toLowerCase()==="busy"}function oE(e){const t=[],n=new Set,r=Array.isArray(e)?e:e?.sessions??e;for(const s of En(r)){const i=X(s.id);if(!i||n.has(i))continue;const a=s.locality==="remote"?"remote":X(s.locality)==="local"?"local":null;if(!a)continue;n.add(i);const c=Pt(s.status)?{code:X(s.status.code),label:X(s.status.label)}:null,l=Pt(s.binding)?{agent:fn(s.binding.agent),team:fn(s.binding.team)}:null,d=Pt(s.opened_by)?{agent:fn(s.opened_by.agent),label:fn(s.opened_by.label),session:fn(s.opened_by.session)}:null;t.push({id:i,name:X(s.name),mtime:Ut(s.mtime)??0,locality:a,owner_device:X(s.owner_device),owner_device_name:X(s.owner_device_name),reachable:Qt(s.reachable,!0),unreachable_reason:X(s.unreachable_reason),live_state:X(s.live_state),archived:Qt(s.archived,!1),created_at:Ut(s.created_at),pinned:Qt(s.pinned,!1),...typeof s.active=="boolean"?{active:s.active}:{},waiting_on:Wn(s.waiting_on),jobs_running:Wn(s.jobs_running),subagents_running:Wn(s.subagents_running),subagents_queued:Wn(s.subagents_queued),...c?{status:c}:{},...l?{binding:l}:{},...d?{opened_by:d}:{}})}return t}function aE(e){const{id:t,name:n,mtime:r,...s}=e;return{...s,session_id:t,title:n,updated_at:r}}function cE(e){if(!Pt(e))return null;const t=X(e.session_id);if(!t)return null;const n=e.mode==="keep"?"keep":"move",r=X(e.new_session_id)||(n==="move"?t:"");return r?{locality:e.locality==="local"?"local":"remote",owner_device:X(e.owner_device),source_retired:Qt(e.source_retired,n==="move"),session_id:t,new_session_id:r,mode:n,phases:En(e.phases).map(s=>({phase:X(s.phase),peer:X(s.peer),progress:typeof s.progress=="number"?s.progress:0}))}:null}const Xv=new Set(["relay_unavailable","deadline_exceeded","peer_unreachable"]);function lE(e){const t=e,n=X(t?.code)||"move_refused",r=typeof t?.status=="number"?t.status:null;return{code:n,sentence:X(t?.message)||"the move was refused",status:r,unconfirmed:r===503||Xv.has(n)}}function dE(e){const t=X(e.name);return t||ae("ui.mesh.mesh_types.device_suffix",{suffix:X(e.device_id).slice(-6)})}function uE(e){const t=X(e.name);return t||ae("ui.mesh.mesh_types.network_suffix",{suffix:X(e.network_id).slice(-6)})}const qv=["the listing budget ran out before this member was probed","the relay is not running, so no device was asked"];function eb(e){const t=e.trim();return t!==""&&qv.includes(t)}function Zd(e){return e.state==="self"?"self":e.reachable?"reached":e.state==="relay_down"?"relay-down":e.state==="handshake_refused"?"handshake-refused":e.linkState==="address_unreachable"?"address-unreachable":e.linkState==="no_endpoint"?"no-endpoint":e.linkState==="not_a_member"?"not-a-member":e.linkState==="not_attempted"||eb(e.reason)?"not-attempted":e.reason?"unanswered":e.sessionCount===null?"unknown":"unanswered"}const fE=()=>ae("ui.mesh.mesh_graph.identity_suspect");function Vd(e){switch(e){case"self":return ae("ui.mesh.mesh_drop.this_device");case"reached":return ae("ui.mesh.mesh_reach.reached");case"relay-down":return ae("ui.mesh.mesh_reach.relay_not_running");case"handshake-refused":return ae("ui.mesh.mesh_reach.handshake_refused");case"address-unreachable":return ae("ui.mesh.mesh_reach.address_unreachable");case"no-endpoint":return ae("ui.mesh.mesh_reach.no_endpoint");case"not-a-member":return ae("ui.mesh.mesh_reach.not_a_member");case"unanswered":return ae("ui.mesh.mesh_reach.no_answer");case"not-attempted":return ae("ui.mesh.mesh_reach.not_asked");default:return ae("ui.mesh.mesh_reach.unknown")}}function pE(e){const t=Zd(e),n=Vd(t);return e.reason?`${n} — ${e.reason}`:n}const hE={self:"text-accent",reached:"text-ink-muted","relay-down":"text-warning","handshake-refused":"text-warning","address-unreachable":"text-warning","no-endpoint":"text-ink-dim","not-a-member":"text-ink-dim",unanswered:"text-warning","not-attempted":"text-ink-dim",unknown:"text-ink-dim"},mE={self:"●",reached:"●","relay-down":"◍","handshake-refused":"◒","address-unreachable":"◔","no-endpoint":"⊘","not-a-member":"◓",unanswered:"◉","not-attempted":"○",unknown:"◌"};function gE(e){const t=e.trim();switch(t){case"ok":return ae("ui.mesh.mesh_reach.attempt_answered");case"connect_failed:ConnectionRefusedError":return ae("ui.mesh.mesh_reach.attempt_nothing_listening");case"connect_failed:TimeoutError":case"no_answer":return ae("ui.mesh.mesh_reach.attempt_no_answer");case"not_attempted":return ae("ui.mesh.mesh_reach.attempt_not_tried");case"bad_endpoint":return ae("ui.mesh.mesh_reach.attempt_bad_address");default:return t.startsWith("connect_failed:")?ae("ui.mesh.mesh_reach.attempt_could_not_connect"):t}}function yE(e){return e.reachable?"":e.remoteRelay==="not_listening"?ae("ui.mesh.mesh_reach.peer_relay_not_running"):e.linkState==="handshake_refused"?ae("ui.mesh.mesh_reach.peer_closed_handshake"):""}function _E(e,t){return e.sessionCount===null?{activity:null,source:"none"}:{activity:t.some(r=>Jv(r))?"working":"idle",source:"derived"}}function tb(e,t){const n={...e};for(const[r,s]of Object.entries(t))(!n[r]||s.at>=n[r].at)&&(n[r]=s);return n}function nb(e,t){if(e.locality!=="remote"||typeof e.owner_device!="string")return e;const n=t[e.owner_device];if(!n)return e.peer_reach||e.link_down?{...e,peer_reach:"unknown",link_down:!1,link_reconnecting:!1,reachable:!1,link_down_reason:null,last_seen_at:null}:e;const r=Zd({state:"unreachable",reachable:n.reachable,reason:n.reason??"",sessionCount:n.session_count??null}),s=r==="unanswered",i=s&&n.redial_state==="reconnecting";return e.peer_reach===r&&e.link_down===s&&(e.link_reconnecting??!1)===i&&e.reachable===n.reachable&&e.last_seen_at===n.last_seen_at&&e.link_down_reason===n.reason?e:{...e,reachable:n.reachable,link_down:s,link_reconnecting:i,peer_reach:r,last_seen_at:n.last_seen_at,link_down_reason:n.reason}}function vE(e,t=Date.now()/1e3){const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return e.link_reconnecting===!0?`${ae("ui.chat.canonical.transcript.reconnecting")} · ${Di(n,t)}`:ae("ui.presence.link_down_last_seen",{age:Di(n,t)})}function Di(e,t){if(e===null)return ae("ui.presence.unknown");const n=Math.max(0,Math.floor(t-e));return n<60?ae("ui.presence.just_now"):n<3600?ae("ui.presence.minutes_ago",{count:Math.floor(n/60)}):n<86400?ae("ui.presence.hours_ago",{count:Math.floor(n/3600)}):ae("ui.presence.days_ago",{count:Math.floor(n/86400)})}function bE(e,t){if(e.link_reconnecting===!0)return ae("ui.chat.canonical.transcript.reconnecting");const n=typeof e.last_seen_at=="number"?e.last_seen_at:null;return ae("ui.presence.link_down_compact",{age:Di(n,t)})}function rb(e,t,n,r){if(r<=n)return{facts:e,watermark:n,removed:[]};const s=Object.fromEntries(Object.entries(e).filter(([,i])=>i.at>r));for(const[i,a]of Object.entries(t))(!s[i]||a.at>=s[i].at)&&(s[i]=a);return{facts:s,watermark:r,removed:Object.keys(e).filter(i=>!s[i])}}function wE(e){return e.peer_reach==="not-attempted"||e.peer_reach==="unknown"?Vd(e.peer_reach):null}function Ni(e,t){return e.map((n,r)=>({id:`${t}:doc:${r}`,attachment:n.digest,filename:n.name??"Attached file",mimeType:n.mime_type??"application/octet-stream",path:n.path??null,storedPath:null,bytes:n.bytes??0}))}const Br=(e,t)=>e instanceof ye?ro(e,t):e instanceof Error?e.message:t,_s="session_unvalidated",sb="This chat is not ready for messages yet, so the message was not sent. Sending works once it is ready.",cs="leading_slash_message",Kd="A message can't start with / — that is a command. Move it below your text, or send it on its own.";function ib(e,t){return e instanceof ye&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const Yd="attachment_read_failed",Qd="store_out_of_space",Jd="store_unavailable";function Dc(e){return e===Qd||e===Jd}const ob="answer_not_sent",Xd="aside_not_answered",qd="aside_still_answering";function zn(e){return e===cs||e===Yd||e===Qd||e===Jd||e===ob||e===Xd||e===qd||e===_s||e===fs}function ab(e){return e instanceof ye&&e.status===409&&Ro(e)===void 0}function eu(e,t=!1){return db(e)||ab(e)&&!t?"not_sent":e instanceof ye&&e.status===404?"gone":"unknown"}function Ro(e){if(e instanceof ye||e instanceof $t)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const Fe={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 SE(e){return e?Fe.gateLock:Fe.sendLock}const kE="Retry",RE="Clear";function cb(e,t,n=!1){const r=eu(e,n),s=t??Ro(e),i=ro(e,Fe.generic);return r==="gone"?{message:Fe.gone,retry:!1,code:s}:r==="not_sent"?s===fs?{message:Fe.busy,retry:!0,code:s}:s===kl?{message:Fe.retiring,retry:!0,code:s}:s===_s?{message:Fe.notReady,retry:!zn(s),code:s}:s===Xd?{message:Fe.asideNotAnswered,retry:!1,code:s}:s===qd?{message:Fe.asideStillAnswering,retry:!1,code:s}:s===cs?{message:Kd,retry:!1,code:s}:{message:i,retry:!1,code:s}:s===Je.transportFailed?{message:Fe.unreachable,retry:!0,code:s}:ps(s)?{message:to[s],retry:!1,code:s}:s===no?{message:Fe.unconfirmed,retry:!zn(s),code:s}:s===ah.runtimeUnreachable?{message:Fe.unconfirmed,retry:!0,code:s}:s?{message:i,retry:!zn(s),code:s}:{message:Fe.unconfirmed,retry:!zn(s),code:s}}function Li(e){return e.trim()}function EE(e,t){if(t.length===0)return Li(e);const n=t.map(r=>`<reply-to>${r.text}</reply-to>`).join(`
|
|
39
39
|
`);return Li(`${n}
|
|
40
|
-
${e}`)}function $i(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function lb(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const s=t.submittedAt;if(s===void 0||s<=0)return!1;const i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=s}function EE(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,i])=>$i(i,t));return(r.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??r[0])?.[0]??`send:${t}`}function Eo(e,t){return t??e??void 0}function tu(e,t,n){return e?t??void 0:n??void 0}function IE(e,t,n){return Eo(e,tu(e,t,n))}function db(e){return e instanceof ye?e.status===413||e.status===422?!0:e.code===fs||e.code===kl||e.code===Je.noCredential||Dc(e.code):e instanceof $t&&(e.code===_s||e.code===Yd||Dc(e.code))}function wr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Eo(e.startsWith("draft:")?e:null,t??n)??e}function ub(e,t){const n=Ne.getState(),r=wr(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function xE(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 r=wr(e,t.sessionId);return Ne.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),ze.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Fe.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!zn(t.heldClaimCode),heldClaimCode:void 0}),!0}function TE(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,s=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!s)return!1;const i=wr(e,t.sessionId);if(n){if(Mc(i,n.recordId))return!1;const c=Wd(i,n.recordId);return c!=="unseen"?(c==="owner"&&ze.getState().retractUndelivered(e,n.recordId),!1):(Oi(i,{id:n.recordId,text:n.text,images:[],documents:Ni(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Mc(i,a)?!1:(Oi(i,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:Ni(t.submittedFiles??[],a)}),!0)}function Nc(e,t,n){Dv(wr(e,t),n)}function fb(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,i)=>s===n[i])}function pb(e,t){return!!t&&e===t}const hb=3,mb=5e3,gb=2e3;async function yb(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=hb||!(n instanceof ye)||n.code!==fs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??gb),mb);await new Promise(s=>setTimeout(s,r))}}async function _b(e){await yb(async()=>{await xe(e)})}async function CE(e,t,n,r,s){const i=ze.getState();if(pb(i.validatingSessionId,n))throw new $t(sb,_s);const a=i.drafts[e];if(a?.pending)return null;const c=Li(t.text),l=a?.submittedText!==void 0&&fb(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,h=l&&a?a.submittedInputMode:t.inputMode,g=l&&a?a.submittedInputPath:t.inputPath,m=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),y=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:m,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:h,submittedInputPath:g,error:void 0,errorCode:void 0,submittedAt:y});const _=Eo(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&Oi(_,{id:m,submittedAt:y,text:c,images:u.map((G,A)=>({id:`${m}:${A}`,data:G.data_b64,attachment:null,mimeType:G.mime_type})),documents:Ni(f??[],m),onPainted:r});let b=l,R=n??d.sessionId,M=null;try{if(!R){if(M="sessions.create",R=await i.createSession(t.cwd,d.target,d.createRequestId,d.model??null,d.warmId,d.peer)??void 0,!R)throw new $t(ze.getState().error??"Chat could not start.");i.updateDraft(e,{sessionId:R}),_&&Av(_,R),i.fetchSessions()}const G=l&&a?.submittedRendered!==void 0?a.submittedRendered:s?await s(R)??c:c;return b=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:G}),R&&Cv(R,m,G),M="sessions.message",await _b({op:"sessions.message",sessionId:R,requestId:m,text:G,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:h,inputPath:g}),i.finishDraft(e,R),ze.setState({error:null}),R}catch(G){ze.setState({error:null});const A=l&&a?.admissionAttempted===!0,O=eu(G,A),S=M==="sessions.message"&&ib(G,c),U=S?cs:Ro(G),V=cb(G,U,A);let ce=!1;const x=R??_??void 0;if(x&&O==="unknown"&&(ce=b&&Wd(x,m)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:O==="unknown"&&b,errorCode:U,error:V.message,errorRetry:V.retry}),ce)return R?(i.finishDraft(e,R),R):null;const C=wr(e,R??d.sessionId),re=_&&_!==C?[_,C]:[C];throw Ne.getState().settleInFlight(re),_&&_!==C&&Ne.getState().returnInFlight(_,C),x&&ji(x,m),e!==x&&ji(e,m),S?new ye(422,Kd,G,cs):G}}const nu=50,Lc="activity",vb=25,bb=500;function wb(e){return e?nu:bb}function $c(e,t){return`${e}:${t}`}function Sb(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function kb(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function Rb(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function Eb(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function Ib(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),s=e.sessions.filter(c=>r.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),a=new Set(i.map(c=>c.session_id));for(const c of s)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function xb(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 r=[...e.sessions],s=new Map(r.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=s.get(i.session_id);if(a===void 0){s.set(i.session_id,r.length),r.push(i);continue}r[a]=e.merge(r[a],i)}return{rows:r,ids:t}}function Wt(e,t){return{...e,...t,...Ob(e,t),...Pb(t,e),attention:mn(e?.attention,t.attention,t.session_id)}}const Tb=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},Cb=e=>e.filter(t=>{if(Tb(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),Uc=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],i=mn(s.attention,n,t);if(i===s.attention)return e;const a=e.slice();return a[r]={...s,attention:i},a},Ab=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Ob(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function Pb(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,s=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof s=="number"&&r>s?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function jb(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){if(i.at<t){r=!0;continue}n[s]=i}return r?n:e}function ai(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(i=>i.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function ru(e){return{...e,sessionId:void 0,pending:!1,error:void 0,errorCode:void 0,errorRetry:void 0,submittedText:void 0,submittedRendered:void 0,submittedAttachments:void 0,submittedImages:void 0,submittedMode:void 0,submittedInputMode:void 0,submittedInputPath:void 0,submittedAt:void 0,admissionAttempted:void 0,undelivered:void 0,warmId:void 0,migratedHeld:void 0,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}function su(e){const t=e.submittedText??e.undelivered?.text,n=e.submittedAttachments??e.undelivered?.attachments??[];return t===void 0&&n.length===0?null:{text:t??"",attachments:[...n]}}function iu(e,t,n){const r=Ne.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=Ne.getState().inputByConversation[t];s&&s.inFlight===void 0&&((s.currentInput??"")!==""||(s.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function Mb(e,t,n){const r=Ne.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function Db(e,t){let n=null;const r=[];for(const[s,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[s]=ru(i),r.push({key:s,sessionId:i.sessionId,payload:su(i)}));return{drafts:n??e,restored:r}}function ou(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function Fc(e,t){return ou(e).filter(n=>t[n.session_id]===void 0)}function ci(e){return typeof e=="string"&&e.length>0?e:null}function Nb(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,r=n(t.total),s=n(t.active),i=n(t.unbound);if(r===null||s===null||i===null||!Array.isArray(t.scopes))return null;const a=[];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||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:i,scopes:a}}function Lb(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Wt(n.get(r.session_id),r)])).values()]}let li=0,dn=null;function $b(e,t,n){const r=dn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const s={limit:e,withCounts:t,invalidated:!1,promise:null};return dn=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let i;try{i=await n(s.limit,s.withCounts)}catch(a){if(s.invalidated)continue;throw a}if(!s.invalidated)return dn===s&&(dn=null),i}}finally{dn===s&&(dn=null)}})(),s.promise}function au(){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 Ub(){const e=au();return e.kind==="session"?e.sessionId:null}function Fb(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 Bb(e,t){const n={...t,...e},{drafts:r,restored:s}=Db(n.drafts,n.forgotten),i=r===n.drafts?n:{...n,drafts:r};for(const l of s)iu(l.key,l.sessionId,l.payload);const a=au();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=Fb(i);return c?{...i,...c}:i}const ze=vr()(hs((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,activeSessionId:Ub(),activeDraftKey:null,drafts:{},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:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const s=Object.entries(r.drafts);return s.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=wb(t().cataloguePageable),r=!1)=>{const s=++li,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await $b(n,r,(l,d)=>xe({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Lc}:{}}));if(s!==li)return;const c=ou(a.sessions);e(l=>{const d={...l.pinFacts};for(const[S,U]of Object.entries(d))U.at>=i||delete d[S];const u=new Set(c.map(S=>S.session_id));let f=!1;const p={...l.forgotten};for(const[S,U]of Object.entries(p))U.at<i&&u.has(S)&&(delete p[S],f=!0);const h=f?p:l.forgotten,g=c.filter(S=>h[S.session_id]===void 0);let m=null;for(const S of g){const U=l.placementFacts[S.session_id];if(U===void 0||U.at>=i)continue;const V=S.locality==="remote"?"remote":S.locality==="local"?"local":null;V!==null&&(m??={...l.placementFacts},m[S.session_id]={locality:V,owner_device:typeof S.owner_device=="string"?S.owner_device:"",at:l.answerSeq+1})}const y=ci(a.next_cursor),_=y===null&&a.truncated!==!0,b=g.map(S=>S.session_id),R=l.sessions.filter(S=>h[S.session_id]===void 0&&(l.pinFacts[S.session_id]?.at??-1)>=i),M=Ib({sessions:l.sessions,scopeIds:Sb(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...kb(l.placementFacts)],tailIds:_?[]:l.head.tailIds,page:g,merge:Lb});let G=M.rows;for(const S of R){const U=l.pinFacts[S.session_id],V=G.findIndex(ce=>ce.session_id===S.session_id);V===-1?G=[...G,{...S,pinned:U.pinned}]:G[V]={...G[V],pinned:U.pinned}}const A=jb(l.archiveFacts,i),O=Nb(a.counts);return{sessions:G,pinFacts:d,archiveFacts:A,...m===null?{}:{placementFacts:m,answerSeq:l.answerSeq+1},forgotten:h,loading:!1,truncated:a.truncated===!0,head:{pageIds:b,tailIds:M.tailIds,nextCursor:y,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:y,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:i},...O===null?{}:{counts:O},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(S=>typeof S=="string"):[]}})}catch(a){s===li&&e({loading:!1,error:Br(a,"Chats could not refresh. Retry to reconnect.")})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await xe({op:"sessions.list",limit:nu,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Lc}:{}}),i=Fc(s.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.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]=Wt(l[p],f)}const u=ci(s.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(i=>({head:{...i.head,loading:!1,error:Br(s,"Could not load more chats.")}}))}}},fetchScopePage:async(n,r,s=null,i=vb)=>{const a=$c(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await xe({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=Fc(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=s!==null&&l.cursor_missing!==!0,h=xb({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Wt}),g=ci(l.next_cursor);return{sessions:h.rows,scopes:{...u.scopes,[a]:{ids:h.ids,nextCursor:g,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:Br(l,"Could not load this group's chats.")}}}})}},clearScope:(n,r)=>{const s=$c(n,r);e(i=>{const a=i.scopes[s];if(a===void 0)return{};const c={...i.scopes};delete c[s];const l=i.activeSessionId,d=new Set(a.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})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,s=r?t().drafts[r]:void 0;if(!r||!s||s.sessionId||s.warmId)return;Ne.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const s={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in s||(s[a]=c);const i=Ne.getState();for(const[a,c]of Object.entries(r.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!1}}}));try{return await xe({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:r?{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||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"Untitled chat",detail:l instanceof ye&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await xe({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>ai(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof ye?r.status:null,i=r instanceof ye?r.code??null:null;return s===404?(e(a=>ai(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:r instanceof ye&&r.message?r.message:"The conversation could not be deleted."}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),i,a,c)=>{try{const l=await xe({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:Br(l,"Chat could not start. Retry with the same draft.")}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...i}=r.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,...ai(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:Ab(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===r?i:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const i=Uc(s.sessions,n,r);return i===s.sessions?s:{...s,sessions:i}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(s=Uc(s,a.slice(8),i))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=Cb(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await xe({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=Rb(t().sessions,t().placementFacts),i=r.unknown.filter(a=>s.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:i}},applySessionStatus:(n,r,s,i)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.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:h,status_epoch:g,...m}=p;return m});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===s&&u.status_epoch===i;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:i}),{...a,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,r=!1)=>{const i=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=tu(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,r)=>{const s=t().activeDraftKey,i=t().stageDraft(n);return Mb(s,i,r),i},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Ne.getState().adoptReturnedText(n),Ne.getState().inputByConversation[n]?.pendingText===void 0&&Ne.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const i=s.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const i=s.drafts[n];if(!i)return{};const a=r??void 0;return(i.peer??void 0)===a?{}:{drafts:{...s.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const i=s.drafts[n];return i?{drafts:{...s.drafts,[n]:{...i,model:r,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const s=r.drafts[n];if(!s||s.sessionId||s.warmId||!r.cwd||s.peer)return;const i=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:i}),xe({op:"sessions.draft",requestId:i,cwd:r.cwd,...s.target?{target:s.target}:{},...s.model?{model:s.model}:{}}).then(a=>{const c=t().drafts[n];c&&!c.warmId&&!c.sessionId&&c.draftRequestId===i&&t().updateDraft(n,{warmId:a.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{ub(n,r);const i={...s.drafts};return delete i[n],{drafts:i,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,i=su(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:ru(c)}}}),iu(n,s,i)},retireDraftsForSession:n=>{for(const[r,s]of Object.entries(t().drafts))r.startsWith("draft:")&&s.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([s,i])=>s.startsWith("draft:")&&i.warmId===n&&!i.sessionId);r.length!==0&&e(s=>{const i={...s.drafts};for(const[a]of r){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(r=>{const s={...r.drafts},i=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=s[n],c=Ne.getState().inputByConversation[n];Ur(n),i&&i!==n&&Ur(i),delete s[n],Ne.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:s,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const s={...r.drafts};let i=!1;const a=[],c={},l={};for(const u of n){if(!(u in s))continue;const f=s[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Ur(u),p&&p!==u&&Ur(p),a.push(u),c[u]=f;const h=Ne.getState().inputByConversation[u];h&&(l[u]=h),delete s[u],Ne.getState().clearAll(u),r.activeDraftKey===u&&(i=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(i=>{const a=r.map(V=>V.id),c=Object.entries(i.drafts).filter(([,V])=>$i(V,n)&&V.undelivered!==void 0&&a.includes(V.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[V,ce]of c){const x=ce.undelivered?.recordId,{undelivered:C,...re}=ce;l[V]=re,x!==void 0&&Nc(V,ce.sessionId,x)}}const d=Object.entries(l).find(([,V])=>$i(V,n)&&V.admissionAttempted===!0&&V.pending!==!0&&V.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,h=a.includes(p);if(!h&&!s)return c.length>0?{drafts:l}:{};if(!h&&!lb(r,f,i.placementFacts[n],i.sessions.find(V=>V.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:g,submittedText:m,submittedAttachments:y,submittedImages:_,submittedMode:b,submittedInputMode:R,submittedInputPath:M,heldClaimCode:G,error:A,errorCode:O,errorRetry:S,...U}=f;return h||ji(n,p),{drafts:{...l,[u]:{...U,...h?{}:{undelivered:{recordId:p,text:m??"",attachments:y??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),Nc(n,s.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(s=>{let i=null,a=null,c=null;for(const l of r){const d=s.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...s.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&s.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=s.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...s.pinFacts},delete i[l.id]),s.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const i=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&s!==void 0?{session_id:n,title:s.title||"Untitled chat",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=i?.title??s?.title,f=i?.updated_at??s?.updated_at;e(p=>({sessions:l===null?p.sessions.map(h=>h.session_id===n?{...h,pinned:r}:h):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await xe({op:"sessions.pin",sessionId:n,pinned:r});let h=!1;return e(g=>{const m=g.pinFacts[n];return m===void 0||m.at!==d?{}:(h=!0,{sessions:g.sessions.map(y=>y.session_id===n?{...y,pinned:p.pinned===!0}:y),pinFacts:{...g.pinFacts,[n]:{...m,pinned:p.pinned===!0}}})}),h}catch(p){return e(h=>{const g=h.pinFacts[n];if(g!==void 0&&g.at!==d)return{};const m={...h.pinFacts};return a===null&&i===void 0?delete m[n]:m[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:h.sessions.map(y=>y.session_id===n?{...y,pinned:c}:y),pinFacts:m,pinFailure:{sessionId:n,pinned:r,title:i?.title||"this chat",detail:ro(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(i=>i.session_id===n.session_id)?r.sessions.map(i=>i.session_id===n.session_id?Wt(i,n):i):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Wt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const S of n)c[S.session_id]?.at<r&&delete c[S.session_id];const l=n.filter(S=>{if(c[S.session_id]||S.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof S.owner_device=="string"&&!a.peerDeviceFacts[S.owner_device])return!1;const U=a.placementFacts[S.session_id];return!U||U.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const S of l){const U=S.locality==="remote"?"remote":S.locality==="local"?"local":null;if(U===null)continue;const V=a.placementFacts[S.session_id];if(V!==void 0){if(V.at>=r)continue}else if(U!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(S.session_id),d[S.session_id]={locality:U,owner_device:U==="remote"&&typeof S.owner_device=="string"?S.owner_device:"",at:p},f=!0}const h=i===void 0?null:rb(a.peerDeviceFacts,s,a.peerDeviceSnapshotAt,i),g=h?.facts??tb(a.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,S])=>S.at>a.peerDeviceSnapshotAt))),m=l.filter(S=>S.locality==="remote");let y=a.sessions,_=!1;const b=[],R=new Map;for(let S=0;S<y.length;S+=1)R.set(y[S].session_id,S);for(const S of m){const U=R.get(S.session_id);if(U===void 0){b.push(S);continue}y[U]!==S&&(_||(y=y.slice(),_=!0),y[U]=Wt(y[U],S))}b.length>0&&(y=[...y,...b]);for(const S of l){if(S.locality==="remote"||!u.has(S.session_id))continue;const U=R.get(S.session_id);U===void 0||y[U]===S||(_||(y=y.slice(),_=!0),y[U]=Wt(y[U],S))}const M=new Set(l.map(S=>S.session_id)),G=new Set;for(const S of l)S.locality==="remote"&&typeof S.owner_device=="string"&&S.owner_device!==""&&S.reachable!==!1&&G.add(S.owner_device);const A=new Set;for(const S of y){if(S.locality!=="remote"||typeof S.owner_device!="string"||!h?.removed.includes(S.owner_device))continue;const U=a.placementFacts[S.session_id];U&&U.at>=(i??0)||(A.add(S.session_id),delete d[S.session_id])}for(const[S,U]of Object.entries(a.placementFacts))U.locality==="remote"&&(M.has(S)||U.at>=r||g[U.owner_device]?.reachable!==!1&&(U.owner_device===""||!G.has(U.owner_device)||(A.add(S),delete d[S])));A.size>0&&(y=y.filter(S=>!A.has(S.session_id)));const O=y.map(S=>nb(S,g));return O.some((S,U)=>S!==y[U])&&(y=O,_=!0),!f&&b.length===0&&!_&&A.size===0&&Object.keys(s).length===0&&i===void 0?{}:{sessions:y,placementFacts:d,peerDeviceFacts:g,peerDeviceSnapshotAt:h?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Bb,partialize:e=>({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}]))})}));function AE(e,t){return t?e.filter(n=>n.archived!==!0):e}function OE(e,t){let n=!1;const r=e.map(s=>{const i=t[s.session_id];return i===void 0||!i.answered||s.archived===i.archived?s:(n=!0,{...s,archived:i.archived})});return n?r:e}function PE(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function jE(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const ME="This backend cannot archive conversations. Update the backend and try again.",DE="This conversation is already archived. Use /unarchive to restore it.",NE="This conversation is not archived, so there is nothing to restore.",LE="This window cannot tell whether that conversation is archived - it is not among the chats listed here. Find it with search and use its row to restore it.";function $E(e,t,n){return n&&e&&t.trim().length>0}function UE(e,t){return t===e}var Sr=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(){}},tn=typeof window>"u"||"Deno"in globalThis;function Qe(){}function Gb(e,t){return typeof e=="function"?e(t):e}function Ui(e){return typeof e=="number"&&e>=0&&e!==1/0}function cu(e,t){return Math.max(e+(t||0)-Date.now(),0)}function vn(e,t){return typeof e=="function"?e(t):e}function it(e,t){return typeof e=="function"?e(t):e}function Bc(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Io(a,t.options))return!1}else if(!hr(t.queryKey,a))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||s&&s!==t.state.fetchStatus||i&&!i(t))}function Gc(e,t){const{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(pr(t.options.mutationKey)!==pr(i))return!1}else if(!hr(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Io(e,t){return(t?.queryKeyHashFn||pr)(e)}function pr(e){return JSON.stringify(e,(t,n)=>Bi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function hr(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>hr(e[n],t[n])):!1}function lu(e,t){if(e===t)return e;const n=Hc(e)&&Hc(t);if(n||Bi(e)&&Bi(t)){const r=n?e:Object.keys(e),s=r.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=lu(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===a&&l===s?e:c}return t}function Fi(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 Hc(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Bi(e){if(!Wc(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Wc(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Wc(e){return Object.prototype.toString.call(e)==="[object Object]"}function Hb(e){return new Promise(t=>{setTimeout(t,e)})}function Gi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?lu(e,t):t}function FE(e){return e}function Wb(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function zb(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xo=Symbol();function du(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xo?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Zb=class extends Sr{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!tn&&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 Zb,Vb=class extends Sr{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!tn&&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}},ls=new Vb;function Hi(){let e,t;const n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}function Kb(e){return Math.min(1e3*2**e,3e4)}function uu(e){return(e??"online")==="online"?ls.isOnline():!0}var fu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function di(e){return e instanceof fu}function pu(e){let t=!1,n=0,r=!1,s;const i=Hi(),a=m=>{r||(p(new fu(m)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>To.isFocused()&&(e.networkMode==="always"||ls.isOnline())&&e.canRun(),u=()=>uu(e.networkMode)&&e.canRun(),f=m=>{r||(r=!0,e.onSuccess?.(m),s?.(),i.resolve(m))},p=m=>{r||(r=!0,e.onError?.(m),s?.(),i.reject(m))},h=()=>new Promise(m=>{s=y=>{(r||d())&&m(y)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),g=()=>{if(r)return;let m;const y=n===0?e.initialPromise:void 0;try{m=y??e.fn()}catch(_){m=Promise.reject(_)}Promise.resolve(m).then(f).catch(_=>{if(r)return;const b=e.retry??(tn?0:3),R=e.retryDelay??Kb,M=typeof R=="function"?R(n,_):R,G=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,_);if(t||!G){p(_);return}n++,e.onFail?.(n,_),Hb(M).then(()=>d()?void 0:h()).then(()=>{t?p(_):g()})})};return{promise:i,cancel:a,continue:()=>(s?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?g():h().then(g),i)}}var Yb=e=>setTimeout(e,0);function Qb(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Yb;const i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var Pe=Qb(),hu=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ui(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(tn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Jb=class extends hu{#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=Xb(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=Gi(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(Qe).catch(Qe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>it(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xo||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||!cu(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,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},s=()=>{const c=du(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(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:s};r(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 a=c=>{di(c)&&c.silent||this.#i({type:"error",error:c}),di(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=pu({initialPromise:t?.initialPromise,fn:i.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,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,...mu(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 r=e.error;return di(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Pe.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function mu(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:uu(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Xb(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var qb=class extends Sr{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??Io(r,t);let i=this.get(s);return i||(i=new Jb({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Pe.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Bc(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Bc(e,n)):t}notify(e){Pe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Pe.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Pe.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ew=class extends hu{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||tw(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#e.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#e.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#e.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){this.#n=pu({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#r({type:"failed",failureCount:r,error:s})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const s=await this.options.onMutate?.(e);s!==this.state.context&&this.#r({type:"pending",context:s,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Pe.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function tw(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var nw=class extends Sr{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new ew({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Gr(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=Gr(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Gr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Gr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Pe.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Gc(t,n))}findAll(e={}){return this.getAll().filter(t=>Gc(e,t))}notify(e){Pe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Pe.batch(()=>Promise.all(e.map(t=>t.continue().catch(Qe))))}};function Gr(e){return e.options.scope?.id}function zc(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=du(t.options,t.fetchOptions),h=async(g,m,y)=>{if(u)return Promise.reject();if(m==null&&g.pages.length)return Promise.resolve(g);const _={client:t.client,queryKey:t.queryKey,pageParam:m,direction:y?"backward":"forward",meta:t.options.meta};f(_);const b=await p(_),{maxPages:R}=t.options,M=y?zb:Wb;return{pages:M(g.pages,b,R),pageParams:M(g.pageParams,m,R)}};if(s&&i.length){const g=s==="backward",m=g?gu:Wi,y={pages:i,pageParams:a},_=m(r,y);c=await h(y,_,g)}else{const g=e??i.length;do{const m=l===0?a[0]??r.initialPageParam:Wi(r,c);if(l>0&&m==null)break;c=await h(c,m),l++}while(l<g)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Wi(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function gu(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function BE(e,t){return t?Wi(e,t)!=null:!1}function GE(e,t){return!t||!e.getPreviousPageParam?!1:gu(e,t)!=null}var rw=class{#t;#e;#n;#r;#s;#a;#o;#i;constructor(e={}){this.#t=e.queryCache||new qb,this.#e=e.mutationCache||new nw,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=To.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=ls.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(vn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=this.#t.get(r.queryHash)?.state.data,a=Gb(t,i);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Pe.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;Pe.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return Pe.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Pe.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Qe).catch(Qe)}invalidateQueries(e,t={}){return Pe.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Pe.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Qe)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Qe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(vn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Qe).catch(Qe)}fetchInfiniteQuery(e){return e.behavior=zc(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Qe).catch(Qe)}ensureInfiniteQueryData(e){return e.behavior=zc(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ls.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(pr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{hr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(pr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{hr(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Io(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===xo&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},sw=class extends Sr{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=Hi(),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),Zc(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zi(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zi(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 it(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&&!Fi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Vc(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||it(this.options.enabled,this.#e)!==it(t.enabled,this.#e)||vn(this.options.staleTime,this.#e)!==vn(t.staleTime,this.#e))&&this.#g();const s=this.#y();r&&(this.#e!==n||it(this.options.enabled,this.#e)!==it(t.enabled,this.#e)||s!==this.#c)&&this.#_(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return ow(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(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),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(Qe)),t}#g(){this.#b();const e=vn(this.options.staleTime,this.#e);if(tn||this.#r.isStale||!Ui(e))return;const n=cu(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}#_(e){this.#w(),this.#c=e,!(tn||it(this.options.enabled,this.#e)===!1||!Ui(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||To.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#_(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,r=this.options,s=this.#r,i=this.#s,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const S=this.hasListeners(),U=!S&&Zc(e,t),V=S&&Vc(e,n,t,r);(U||V)&&(u={...u,...mu(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:g,status:m}=u;p=u.data;let y=!1;if(t.placeholderData!==void 0&&p===void 0&&m==="pending"){let S;s?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(S=s.data,y=!0):S=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,S!==void 0&&(m="success",p=Gi(s?.data,S,t),f=!0)}if(t.select&&p!==void 0&&!y)if(s&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Gi(s?.data,p,t),this.#f=p,this.#i=null}catch(S){this.#i=S}this.#i&&(h=this.#i,p=this.#f,g=Date.now(),m="error");const _=u.fetchStatus==="fetching",b=m==="pending",R=m==="error",M=b&&_,G=p!==void 0,O={status:m,fetchStatus:u.fetchStatus,isPending:b,isSuccess:m==="success",isError:R,isInitialLoading:M,isLoading:M,data:p,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:g,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:_,isRefetching:_&&!b,isLoadingError:R&&!G,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:R&&G,isStale:Co(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const S=ce=>{O.status==="error"?ce.reject(O.error):O.data!==void 0&&ce.resolve(O.data)},U=()=>{const ce=this.#o=O.promise=Hi();S(ce)},V=this.#o;switch(V.status){case"pending":e.queryHash===n.queryHash&&S(V);break;case"fulfilled":(O.status==="error"||O.data!==V.value)&&U();break;case"rejected":(O.status!=="error"||O.error!==V.reason)&&U();break}}return O}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),Fi(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const i=new Set(s??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(a=>{const c=a;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.#v()}#k(e){Pe.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function iw(e,t){return it(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Zc(e,t){return iw(e,t)||e.state.data!==void 0&&zi(e,t,t.refetchOnMount)}function zi(e,t,n){if(it(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Co(e,t)}return!1}function Vc(e,t,n,r){return(e!==t||it(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Co(e,n)}function Co(e,t){return it(t.enabled,e)!==!1&&e.isStaleByTime(vn(t.staleTime,e))}function ow(e,t){return!Fi(e.getCurrentResult(),t)}var Ao=v.createContext(void 0),aw=e=>{const t=v.useContext(Ao);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},HE=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Xu.jsx(Ao.Provider,{value:e,children:t})),yu=v.createContext(!1),cw=()=>v.useContext(yu);yu.Provider;function lw(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var dw=v.createContext(lw()),uw=()=>v.useContext(dw);function fw(e,t){return typeof e=="function"?e(...t):!!e}function Kc(){}var pw=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},hw=e=>{v.useEffect(()=>{e.clearReset()},[e])},mw=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||fw(n,[e.error,r])),gw=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)))},yw=(e,t)=>e.isLoading&&e.isFetching&&!t,_w=(e,t)=>e?.suspense&&t.isPending,Yc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function vw(e,t,n){const r=aw(n),s=cw(),i=uw(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=s?"isRestoring":"optimistic",gw(a),pw(a,i),hw(i);const c=!r.getQueryCache().get(a.queryHash),[l]=v.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!s&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(f=>{const p=u?l.subscribe(Pe.batchCalls(f)):Kc;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(a)},[a,l]),_w(a,d))throw Yc(a,l,i);if(mw({result:d,errorResetBoundary:i,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!tn&&yw(d,s)&&(c?Yc(a,l,i):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Kc).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function _u(e,t){return vw(e,sw,t)}/**
|
|
40
|
+
${e}`)}function $i(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function lb(e,t,n,r){if(t.peer!==void 0||n?.locality==="remote"||r?.locality==="remote")return!1;const s=t.submittedAt;if(s===void 0||s<=0)return!1;const i=e[0]?.ts;return i===void 0||i<=0?!1:i*1e3<=s}function IE(e,t,n){if(e)return e;if(!t)return null;const r=Object.entries(n).filter(([,i])=>$i(i,t));return(r.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??r[0])?.[0]??`send:${t}`}function Eo(e,t){return t??e??void 0}function tu(e,t,n){return e?t??void 0:n??void 0}function xE(e,t,n){return Eo(e,tu(e,t,n))}function db(e){return e instanceof ye?e.status===413||e.status===422?!0:e.code===fs||e.code===kl||e.code===Je.noCredential||Dc(e.code):e instanceof $t&&(e.code===_s||e.code===Yd||Dc(e.code))}function wr(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Eo(e.startsWith("draft:")?e:null,t??n)??e}function ub(e,t){const n=Ne.getState(),r=wr(e,t),s=r===""||r===e?[e]:[e,r];n.settleInFlight(s),r!==""&&r!==e&&n.inputByConversation[e]&&n.returnInFlight(e,r)}function TE(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 r=wr(e,t.sessionId);return Ne.getState().returnPayload(r,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),ze.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:Fe.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!zn(t.heldClaimCode),heldClaimCode:void 0}),!0}function CE(e,t){if(!t)return!1;const n=t.undelivered,r=t.submittedText,s=r!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!s)return!1;const i=wr(e,t.sessionId);if(n){if(Mc(i,n.recordId))return!1;const c=Wd(i,n.recordId);return c!=="unseen"?(c==="owner"&&ze.getState().retractUndelivered(e,n.recordId),!1):(Oi(i,{id:n.recordId,text:n.text,images:[],documents:Ni(t.submittedFiles??[],n.recordId),settled:!0,submittedAt:t.submittedAt}),!0)}if(r===void 0)return!1;const a=t.admissionRequestId;return Mc(i,a)?!1:(Oi(i,{id:a,text:t.submittedRendered??r,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${a}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type})),documents:Ni(t.submittedFiles??[],a)}),!0)}function Nc(e,t,n){Dv(wr(e,t),n)}function fb(e,t,n){if(e.submittedText!==t)return!1;const r=e.submittedAttachments??[];return r.length!==n.length?!1:r.every((s,i)=>s===n[i])}function pb(e,t){return!!t&&e===t}const hb=3,mb=5e3,gb=2e3;async function yb(e){for(let t=0;;t++)try{return await e()}catch(n){if(t>=hb||!(n instanceof ye)||n.code!==fs)throw n;const r=Math.min(Math.max(0,n.retryAfterMs??gb),mb);await new Promise(s=>setTimeout(s,r))}}async function _b(e){await yb(async()=>{await xe(e)})}async function AE(e,t,n,r,s){const i=ze.getState();if(pb(i.validatingSessionId,n))throw new $t(sb,_s);const a=i.drafts[e];if(a?.pending)return null;const c=Li(t.text),l=a?.submittedText!==void 0&&fb(a,c,t.attachments),d=a??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?a?.submittedImages??t.images:t.images,f=l?a?.submittedFiles??t.files:t.files,p=l?a?.submittedMode??t.mode:t.mode,h=l&&a?a.submittedInputMode:t.inputMode,g=l&&a?a.submittedInputPath:t.inputPath,m=a?.submittedText===void 0||l?a?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),y=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:m,submittedRendered:l?a?.submittedRendered:void 0,migratedHeld:a?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedFiles:f,submittedMode:p,submittedInputMode:h,submittedInputPath:g,error:void 0,errorCode:void 0,submittedAt:y});const _=Eo(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&Oi(_,{id:m,submittedAt:y,text:c,images:u.map((G,A)=>({id:`${m}:${A}`,data:G.data_b64,attachment:null,mimeType:G.mime_type})),documents:Ni(f??[],m),onPainted:r});let b=l,R=n??d.sessionId,M=null;try{if(!R){if(M="sessions.create",R=await i.createSession(t.cwd,d.target,d.createRequestId,d.model??null,d.warmId,d.peer)??void 0,!R)throw new $t(ze.getState().error??"Chat could not start.");i.updateDraft(e,{sessionId:R}),_&&Av(_,R),i.fetchSessions()}const G=l&&a?.submittedRendered!==void 0?a.submittedRendered:s?await s(R)??c:c;return b=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:G}),R&&Cv(R,m,G),M="sessions.message",await _b({op:"sessions.message",sessionId:R,requestId:m,text:G,images:u.length?u:void 0,...f?.length?{files:f}:{},mode:p,inputMode:h,inputPath:g}),i.finishDraft(e,R),ze.setState({error:null}),R}catch(G){ze.setState({error:null});const A=l&&a?.admissionAttempted===!0,O=eu(G,A),S=M==="sessions.message"&&ib(G,c),U=S?cs:Ro(G),V=cb(G,U,A);let ce=!1;const x=R??_??void 0;if(x&&O==="unknown"&&(ce=b&&Wd(x,m)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:O==="unknown"&&b,errorCode:U,error:V.message,errorRetry:V.retry}),ce)return R?(i.finishDraft(e,R),R):null;const C=wr(e,R??d.sessionId),re=_&&_!==C?[_,C]:[C];throw Ne.getState().settleInFlight(re),_&&_!==C&&Ne.getState().returnInFlight(_,C),x&&ji(x,m),e!==x&&ji(e,m),S?new ye(422,Kd,G,cs):G}}const nu=50,Lc="activity",vb=25,bb=500;function wb(e){return e?nu:bb}function $c(e,t){return`${e}:${t}`}function Sb(e){const t=new Set;for(const n of Object.values(e))for(const r of n.ids)t.add(r);return t}function kb(e){const t=[];for(const[n,r]of Object.entries(e))r.locality==="remote"&&t.push(n);return t}function Rb(e,t){const n=new Set;for(const[r,s]of Object.entries(t))s.locality==="remote"&&n.add(r);for(const r of e)r.locality==="remote"&&n.add(r.session_id);return n}function Eb(e,t,n){if(t[n]?.locality==="remote")return!0;for(const r of e)if(r.session_id===n&&r.locality==="remote")return!0;return!1}function Ib(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),r=new Set(e.page.map(c=>c.session_id)),s=e.sessions.filter(c=>r.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),a=new Set(i.map(c=>c.session_id));for(const c of s)a.has(c.session_id)||(a.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>a.has(c))}}function xb(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 r=[...e.sessions],s=new Map(r.map((i,a)=>[i.session_id,a]));for(const i of e.page){const a=s.get(i.session_id);if(a===void 0){s.set(i.session_id,r.length),r.push(i);continue}r[a]=e.merge(r[a],i)}return{rows:r,ids:t}}function Wt(e,t){return{...e,...t,...Ob(e,t),...Pb(t,e),attention:mn(e?.attention,t.attention,t.session_id)}}const Tb=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},Cb=e=>e.filter(t=>{if(Tb(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),Uc=(e,t,n)=>{const r=e.findIndex(c=>c.session_id===t);if(r<0)return e;const s=e[r],i=mn(s.attention,n,t);if(i===s.attention)return e;const a=e.slice();return a[r]={...s,attention:i},a},Ab=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Ob(e,t){const n=r=>typeof r?.status_revision=="number"&&typeof r?.status_epoch=="string"?{status_revision:r.status_revision,status_epoch:r.status_epoch}:void 0;return n(t)??n(e)??{}}function Pb(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,r=t?.status_revision,s=e.status_revision;return t?.status!==void 0&&n&&typeof r=="number"&&typeof s=="number"&&r>s?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function jb(e,t){const n={};let r=!1;for(const[s,i]of Object.entries(e)){if(i.at<t){r=!0;continue}n[s]=i}return r?n:e}function ai(e,t){const n={...e.archiveFacts};delete n[t];const r={...e.placementFacts};delete r[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(i=>i.session_id!==t),archiveFacts:n,placementFacts:r,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(i=>i.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function ru(e){return{...e,sessionId:void 0,pending:!1,error:void 0,errorCode:void 0,errorRetry:void 0,submittedText:void 0,submittedRendered:void 0,submittedAttachments:void 0,submittedImages:void 0,submittedMode:void 0,submittedInputMode:void 0,submittedInputPath:void 0,submittedAt:void 0,admissionAttempted:void 0,undelivered:void 0,warmId:void 0,migratedHeld:void 0,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}function su(e){const t=e.submittedText??e.undelivered?.text,n=e.submittedAttachments??e.undelivered?.attachments??[];return t===void 0&&n.length===0?null:{text:t??"",attachments:[...n]}}function iu(e,t,n){const r=Ne.getState();if(t&&t!==e){r.adoptReturnedText(t);const s=Ne.getState().inputByConversation[t];s&&s.inFlight===void 0&&((s.currentInput??"")!==""||(s.attachments?.length??0)>0)&&r.returnInFlight(t,e)}n&&r.returnPayload(e,{text:n.text,attachments:n.attachments,replies:[]})}function Mb(e,t,n){const r=Ne.getState(),s=n??(e?r.getCurrentInput(e):"");s&&r.setComposerText(t,s),e&&e!==t&&r.setComposerText(e,"")}function Db(e,t){let n=null;const r=[];for(const[s,i]of Object.entries(e))!i.sessionId||t[i.sessionId]===void 0||(n??={...e},n[s]=ru(i),r.push({key:s,sessionId:i.sessionId,payload:su(i)}));return{drafts:n??e,restored:r}}function ou(e){return e.map(({id:t,name:n,mtime:r,...s})=>({...s,session_id:t,title:n,updated_at:r}))}function Fc(e,t){return ou(e).filter(n=>t[n.session_id]===void 0)}function ci(e){return typeof e=="string"&&e.length>0?e:null}function Nb(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,r=n(t.total),s=n(t.active),i=n(t.unbound);if(r===null||s===null||i===null||!Array.isArray(t.scopes))return null;const a=[];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||a.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:r,active:s,unbound:i,scopes:a}}function Lb(e,t){const n=new Map(e.map(r=>[r.session_id,r]));return[...new Map(t.map(r=>[r.session_id,Wt(n.get(r.session_id),r)])).values()]}let li=0,dn=null;function $b(e,t,n){const r=dn;if(r)return r.invalidated=!0,r.limit=e,r.withCounts=t,r.promise;const s={limit:e,withCounts:t,invalidated:!1,promise:null};return dn=s,s.promise=(async()=>{try{for(;;){s.invalidated=!1;let i;try{i=await n(s.limit,s.withCounts)}catch(a){if(s.invalidated)continue;throw a}if(!s.invalidated)return dn===s&&(dn=null),i}}finally{dn===s&&(dn=null)}})(),s.promise}function au(){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 Ub(){const e=au();return e.kind==="session"?e.sessionId:null}function Fb(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 Bb(e,t){const n={...t,...e},{drafts:r,restored:s}=Db(n.drafts,n.forgotten),i=r===n.drafts?n:{...n,drafts:r};for(const l of s)iu(l.key,l.sessionId,l.payload);const a=au();if(a.kind==="session")return{...i,activeSessionId:a.sessionId};if(a.kind==="catalogue")return{...i,activeSessionId:null};const c=Fb(i);return c?{...i,...c}:i}const ze=vr()(hs((e,t)=>({sessions:[],cataloguePageable:!1,catalogueActivityHead:!1,draftWarmable:!1,activeSessionId:Ub(),activeDraftKey:null,drafts:{},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:{},placementFacts:{},peerDeviceFacts:{},peerDeviceSnapshotAt:0,forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,bulkReadDeferral:null,stagedByDiscard:null,deleteCandidate:null,archiveCandidate:null,error:null,cwd:"~",setCwd:n=>e(r=>{const s=Object.entries(r.drafts);return s.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(s.map(([i,a])=>a.sessionId?[i,a]:[i,{...a,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=wb(t().cataloguePageable),r=!1)=>{const s=++li,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const a=await $b(n,r,(l,d)=>xe({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{},...t().catalogueActivityHead?{sort:Lc}:{}}));if(s!==li)return;const c=ou(a.sessions);e(l=>{const d={...l.pinFacts};for(const[S,U]of Object.entries(d))U.at>=i||delete d[S];const u=new Set(c.map(S=>S.session_id));let f=!1;const p={...l.forgotten};for(const[S,U]of Object.entries(p))U.at<i&&u.has(S)&&(delete p[S],f=!0);const h=f?p:l.forgotten,g=c.filter(S=>h[S.session_id]===void 0);let m=null;for(const S of g){const U=l.placementFacts[S.session_id];if(U===void 0||U.at>=i)continue;const V=S.locality==="remote"?"remote":S.locality==="local"?"local":null;V!==null&&(m??={...l.placementFacts},m[S.session_id]={locality:V,owner_device:typeof S.owner_device=="string"?S.owner_device:"",at:l.answerSeq+1})}const y=ci(a.next_cursor),_=y===null&&a.truncated!==!0,b=g.map(S=>S.session_id),R=l.sessions.filter(S=>h[S.session_id]===void 0&&(l.pinFacts[S.session_id]?.at??-1)>=i),M=Ib({sessions:l.sessions,scopeIds:Sb(l.scopes),keepIds:[...l.activeSessionId===null?[]:[l.activeSessionId],...kb(l.placementFacts)],tailIds:_?[]:l.head.tailIds,page:g,merge:Lb});let G=M.rows;for(const S of R){const U=l.pinFacts[S.session_id],V=G.findIndex(ce=>ce.session_id===S.session_id);V===-1?G=[...G,{...S,pinned:U.pinned}]:G[V]={...G[V],pinned:U.pinned}}const A=jb(l.archiveFacts,i),O=Nb(a.counts);return{sessions:G,pinFacts:d,archiveFacts:A,...m===null?{}:{placementFacts:m,answerSeq:l.answerSeq+1},forgotten:h,loading:!1,truncated:a.truncated===!0,head:{pageIds:b,tailIds:M.tailIds,nextCursor:y,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:y,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:i},...O===null?{}:{counts:O},statusUnavailable:Array.isArray(a.degraded)?a.degraded.filter(S=>typeof S=="string"):[]}})}catch(a){s===li&&e({loading:!1,error:Br(a,"Chats could not refresh. Retry to reconnect.")})}},fetchCatalogueTail:async()=>{const n=t().head,r=n.tailCursor;if(!(r===null||n.loading)){e(s=>({head:{...s.head,loading:!0,error:null,tailStarted:!0,tailCursor:r}}));try{const s=await xe({op:"sessions.list",limit:nu,include_archived:!0,cursor:r,...t().catalogueActivityHead?{sort:Lc}:{}}),i=Fc(s.sessions,t().forgotten);e(a=>{const c=new Map(a.sessions.map((f,p)=>[f.session_id,p])),l=[...a.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]=Wt(l[p],f)}const u=ci(s.next_cursor);return{sessions:l,head:{...a.head,tailIds:[...a.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(s){e(i=>({head:{...i.head,loading:!1,error:Br(s,"Could not load more chats.")}}))}}},fetchScopePage:async(n,r,s=null,i=vb)=>{const a=$c(n,r);if(t().scopes[a]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[a]:{ids:l.scopes[a]?.ids??[],nextCursor:l.scopes[a]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await xe({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:r,...s===null?{}:{cursor:s}}),d=Fc(l.sessions,t().forgotten);e(u=>{const f=u.scopes[a];if(f===void 0||f.at!==c)return{};const p=s!==null&&l.cursor_missing!==!0,h=xb({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:Wt}),g=ci(l.next_cursor);return{sessions:h.rows,scopes:{...u.scopes,[a]:{ids:h.ids,nextCursor:g,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[a];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[a]:{...u,loading:!1,error:Br(l,"Could not load this group's chats.")}}}})}},clearScope:(n,r)=>{const s=$c(n,r);e(i=>{const a=i.scopes[s];if(a===void 0)return{};const c={...i.scopes};delete c[s];const l=i.activeSessionId,d=new Set(a.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})},setCatalogueActivityHead:n=>{t().catalogueActivityHead!==n&&e({catalogueActivityHead:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const r=t().activeDraftKey,s=r?t().drafts[r]:void 0;if(!r||!s||s.sessionId||s.warmId)return;Ne.getState().inputByConversation[r]?.currentInput&&t().ensureDraftWarm(r)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},raiseBulkReadDeferral:n=>{e(r=>({bulkReadDeferral:{count:n,at:r.answerSeq+1}}))},clearBulkReadDeferral:()=>{e({bulkReadDeferral:null})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const r=n.draftsUndo;if(!r)return{};const s={...n.drafts};for(const[a,c]of Object.entries(r.drafts))a in s||(s[a]=c);const i=Ne.getState();for(const[a,c]of Object.entries(r.composer)){const l=i.inputByConversation[a];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(a,c)}return{drafts:s,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,r,s)=>{const i=t().answerSeq+1,a=t().archiveFacts[n]??null,c=s??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!1}}}));try{return await xe({op:"sessions.archive",sessionId:n,archived:r}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:r,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:r?{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||(a?.answered===!0?f[n]=a:(delete f[n],a!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:r,title:c||"Untitled chat",detail:l instanceof ye&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await xe({op:"sessions.delete",sessionId:n,confirmed:!0}),e(r=>ai(r,n)),t().retireDraftsForSession(n),{ok:!0}}catch(r){const s=r instanceof ye?r.status:null,i=r instanceof ye?r.code??null:null;return s===404?(e(a=>ai(a,n)),t().retireDraftsForSession(n),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:r instanceof ye&&r.message?r.message:"The conversation could not be deleted."}}},requestSessionDelete:n=>e({deleteCandidate:n}),requestArchiveConfirm:n=>e({archiveCandidate:n}),createSession:async(n,r,s=crypto.randomUUID(),i,a,c)=>{try{const l=await xe({op:"sessions.create",requestId:s,cwd:n,...r?{target:r}:{},...i?{model:i}:{},...a?{draftId:a}:{},...c?{peer:c}:{}});return t().upsertSession({session_id:l.session_id,cwd:n,binding:l.binding}),c&&t().settlePlacement(l.session_id,{locality:"remote",owner_device:c}),l.session_id}catch(l){throw e({error:Br(l,"Chat could not start. Retry with the same draft.")}),l}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,r=Date.now())=>e(s=>({stoppedTurns:{...s.stoppedTurns,[n]:r}})),clearTurnStopped:n=>e(r=>{if(!(n in r.stoppedTurns))return r;const{[n]:s,...i}=r.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,...ai(t(),n)}),t().retireDraftsForSession(n))},rearmReadAck:n=>{e(r=>({readAckRearm:Ab(r.readAckRearm,n)}))},publishReadAckNotice:(n,r,s)=>{e(i=>{const a=i.readAckNotice;return a?.sessionId===n&&a.kind===r?i:{readAckNotice:{sessionId:n,kind:r,revision:(a?.revision??0)+1,reason:s}}})},clearReadAckNotice:n=>{e(r=>r.readAckNotice?.sessionId===n?{readAckNotice:null}:r)},applyAttention:(n,r)=>{e(s=>{const i=Uc(s.sessions,n,r);return i===s.sessions?s:{...s,sessions:i}})},applyAttentionMany:n=>{e(r=>{let s=r.sessions;for(const i of n){const a=i?.conversation_id;typeof a!="string"||!a.startsWith("session/")||(s=Uc(s,a.slice(8),i))}return s===r.sessions?r:{...r,sessions:s}})},markAllRead:async()=>{const n=Cb(t().sessions).map(a=>({sessionId:a.session_id,completionToken:a.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0,deferred:0};const r=await xe({op:"attention.seen",items:n});t().applyAttentionMany(r.read);const s=Rb(t().sessions,t().placementFacts),i=r.unknown.filter(a=>s.has(a)).length;return{attempted:n.length,cleared:r.read.length,superseded:r.superseded.length,unknown:r.unknown.length,deferred:i}},applySessionStatus:(n,r,s,i)=>{e(a=>{const c=a.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=a.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:h,status_epoch:g,...m}=p;return m});if(c<0)return l?{...a,sessions:d}:a;const u=d[c],f=u.status?.code===r.code&&u.status?.label===r.label&&u.status_revision===s&&u.status_epoch===i;return f&&!l?a:(f||(d[c]={...u,status:r,status_revision:s,status_epoch:i}),{...a,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,r=!1)=>{const i=(!r&&n?`draft:${n.kind}:${n.name}`:null)??`draft:${crypto.randomUUID()}`,a=t().drafts[i],c=tu(t().activeDraftKey,t().activeDraftKey?t().drafts[t().activeDraftKey]?.sessionId:void 0,t().activeSessionId);if(a?.sessionId&&!a.pending&&a.sessionId!==c){const d=t().drafts[`send:${a.sessionId}`]?`draft:${crypto.randomUUID()}`:`send:${a.sessionId}`;e(u=>{const f={...u.drafts};return delete f[i],f[d]={...a,key:d},{drafts:f}})}const l=t().drafts[i];return e(d=>({activeDraftKey:i,validatingSessionId:null,error:null,drafts:{...d.drafts,[i]:l??{key:i,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),i},restageDraft:(n,r)=>{const s=t().activeDraftKey,i=t().stageDraft(n);return Mb(s,i,r),i},startNewChat:n=>{const r=t().stageDraft();return e({activeSessionId:null,validatingSessionId:null}),n&&(Ne.getState().adoptReturnedText(n),Ne.getState().inputByConversation[n]?.pendingText===void 0&&Ne.getState().returnInFlight(n,r)),r},updateDraft:(n,r)=>e(s=>{const i=s.drafts[n],a=r.key!==void 0&&r.createRequestId!==void 0&&r.admissionRequestId!==void 0;return!i&&!a?{}:{drafts:{...s.drafts,[n]:{...s.drafts[n],...r}}}}),setDraftPeer:(n,r)=>e(s=>{const i=s.drafts[n];if(!i)return{};const a=r??void 0;return(i.peer??void 0)===a?{}:{drafts:{...s.drafts,[n]:{...i,peer:a,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}}),setDraftModel:(n,r)=>e(s=>{const i=s.drafts[n];return i?{drafts:{...s.drafts,[n]:{...i,model:r,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const r=t();if(!r.draftWarmable)return;const s=r.drafts[n];if(!s||s.sessionId||s.warmId||!r.cwd||s.peer)return;const i=s.draftRequestId??crypto.randomUUID();s.draftRequestId||t().updateDraft(n,{draftRequestId:i}),xe({op:"sessions.draft",requestId:i,cwd:r.cwd,...s.target?{target:s.target}:{},...s.model?{model:s.model}:{}}).then(a=>{const c=t().drafts[n];c&&!c.warmId&&!c.sessionId&&c.draftRequestId===i&&t().updateDraft(n,{warmId:a.draft_id})}).catch(()=>{})},finishDraft:(n,r)=>e(s=>{ub(n,r);const i={...s.drafts};return delete i[n],{drafts:i,...s.activeDraftKey===n?{activeDraftKey:null,activeSessionId:r}:{}}}),retireDraftSession:n=>{const r=t().drafts[n];if(!r?.sessionId||r.pending)return;const s=r.sessionId,i=su(r);e(a=>{const c=a.drafts[n];return!c?.sessionId||c.pending?{}:{drafts:{...a.drafts,[n]:ru(c)}}}),iu(n,s,i)},retireDraftsForSession:n=>{for(const[r,s]of Object.entries(t().drafts))r.startsWith("draft:")&&s.sessionId===n&&t().retireDraftSession(r)},retireDraftWarm:n=>{const r=Object.entries(t().drafts).filter(([s,i])=>s.startsWith("draft:")&&i.warmId===n&&!i.sessionId);r.length!==0&&e(s=>{const i={...s.drafts};for(const[a]of r){const c=i[a];!c||c.warmId!==n||c.sessionId||(i[a]={...c,warmId:void 0,draftRequestId:crypto.randomUUID()})}return{drafts:i}})},discardDraft:n=>e(r=>{const s={...r.drafts},i=s[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),a=s[n],c=Ne.getState().inputByConversation[n];Ur(n),i&&i!==n&&Ur(i),delete s[n],Ne.getState().clearAll(n);const l=a?{at:r.answerSeq+1,keys:[n],drafts:{[n]:a},composer:c?{[n]:c}:{}}:null;return{drafts:s,...l?{answerSeq:l.at,draftsUndo:l}:{},...r.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(r=>{const s={...r.drafts};let i=!1;const a=[],c={},l={};for(const u of n){if(!(u in s))continue;const f=s[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);Ur(u),p&&p!==u&&Ur(p),a.push(u),c[u]=f;const h=Ne.getState().inputByConversation[u];h&&(l[u]=h),delete s[u],Ne.getState().clearAll(u),r.activeDraftKey===u&&(i=!0)}if(a.length===0)return{};const d=r.answerSeq+1;return{drafts:s,answerSeq:d,draftsUndo:{at:d,keys:a,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,r,s)=>e(i=>{const a=r.map(V=>V.id),c=Object.entries(i.drafts).filter(([,V])=>$i(V,n)&&V.undelivered!==void 0&&a.includes(V.undelivered.recordId));let l=i.drafts;if(c.length>0){l={...l};for(const[V,ce]of c){const x=ce.undelivered?.recordId,{undelivered:C,...re}=ce;l[V]=re,x!==void 0&&Nc(V,ce.sessionId,x)}}const d=Object.entries(l).find(([,V])=>$i(V,n)&&V.admissionAttempted===!0&&V.pending!==!0&&V.submittedText!==void 0);if(!d)return c.length>0?{drafts:l}:{};const[u,f]=d,p=f.admissionRequestId,h=a.includes(p);if(!h&&!s)return c.length>0?{drafts:l}:{};if(!h&&!lb(r,f,i.placementFacts[n],i.sessions.find(V=>V.session_id===n)))return c.length>0?{drafts:l}:{};const{admissionAttempted:g,submittedText:m,submittedAttachments:y,submittedImages:_,submittedMode:b,submittedInputMode:R,submittedInputPath:M,heldClaimCode:G,error:A,errorCode:O,errorRetry:S,...U}=f;return h||ji(n,p),{drafts:{...l,[u]:{...U,...h?{}:{undelivered:{recordId:p,text:m??"",attachments:y??[]}},admissionRequestId:crypto.randomUUID()}}}}),retractUndelivered:(n,r)=>{const s=t().drafts[n];!s||s.undelivered?.recordId!==r||(e(i=>{const{undelivered:a,...c}=i.drafts[n];return{drafts:{...i.drafts,[n]:c}}}),Nc(n,s.sessionId,r))},bindSession:(n,r)=>t().setActiveSession(r),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,r)=>e(s=>{let i=null,a=null,c=null;for(const l of r){const d=s.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...s.archiveFacts},delete c[l.id]),!(d!==void 0&&d.at>=n)&&typeof l.archived=="boolean"&&s.sessions.some(f=>f.session_id===l.id&&f.archived!==l.archived)){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.archived=l.archived===!0)}if(typeof l.pinned!="boolean")continue;const u=s.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...s.pinFacts},delete i[l.id]),s.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){a=a??s.sessions.map(f=>({...f}));for(const f of a)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&a===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...a===null?{}:{sessions:a},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,r,s)=>{const i=t().sessions.find(p=>p.session_id===n),a=t().pinFacts[n]??null,c=i===void 0?a?.pinned??!1:i.pinned===!0,l=i===void 0&&s!==void 0?{session_id:n,title:s.title||"Untitled chat",updated_at:s.updated_at,pinned:r}:null,d=t().beginAnswer(),u=i?.title??s?.title,f=i?.updated_at??s?.updated_at;e(p=>({sessions:l===null?p.sessions.map(h=>h.session_id===n?{...h,pinned:r}:h):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:r,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await xe({op:"sessions.pin",sessionId:n,pinned:r});let h=!1;return e(g=>{const m=g.pinFacts[n];return m===void 0||m.at!==d?{}:(h=!0,{sessions:g.sessions.map(y=>y.session_id===n?{...y,pinned:p.pinned===!0}:y),pinFacts:{...g.pinFacts,[n]:{...m,pinned:p.pinned===!0}}})}),h}catch(p){return e(h=>{const g=h.pinFacts[n];if(g!==void 0&&g.at!==d)return{};const m={...h.pinFacts};return a===null&&i===void 0?delete m[n]:m[n]={pinned:c,at:Math.max(a?.at??0,d),title:a?.title??u,updated_at:a?.updated_at??f},{sessions:h.sessions.map(y=>y.session_id===n?{...y,pinned:c}:y),pinFacts:m,pinFailure:{sessionId:n,pinned:r,title:i?.title||"this chat",detail:ro(p,"")}}}),!1}},upsertSession:n=>e(r=>({sessions:r.sessions.some(i=>i.session_id===n.session_id)?r.sessions.map(i=>i.session_id===n.session_id?Wt(i,n):i):[...r.sessions,n]})),settlePlacement:(n,r)=>{const s=t().beginAnswer();e(i=>({sessions:i.sessions.map(a=>a.session_id===n?Wt(a,{session_id:n,locality:r.locality,owner_device:r.owner_device}):a),placementFacts:{...i.placementFacts,[n]:{locality:r.locality,owner_device:r.owner_device,at:s}}}))},settlePeerCatalogue:(n,r,s={},i=void 0)=>{e(a=>{const c={...a.forgotten};for(const S of n)c[S.session_id]?.at<r&&delete c[S.session_id];const l=n.filter(S=>{if(c[S.session_id]||S.locality==="remote"&&a.peerDeviceSnapshotAt>r&&typeof S.owner_device=="string"&&!a.peerDeviceFacts[S.owner_device])return!1;const U=a.placementFacts[S.session_id];return!U||U.at<r}),d={...a.placementFacts},u=new Set;let f=!1,p=0;for(const S of l){const U=S.locality==="remote"?"remote":S.locality==="local"?"local":null;if(U===null)continue;const V=a.placementFacts[S.session_id];if(V!==void 0){if(V.at>=r)continue}else if(U!=="remote")continue;p=p===0?a.answerSeq+1:p,u.add(S.session_id),d[S.session_id]={locality:U,owner_device:U==="remote"&&typeof S.owner_device=="string"?S.owner_device:"",at:p},f=!0}const h=i===void 0?null:rb(a.peerDeviceFacts,s,a.peerDeviceSnapshotAt,i),g=h?.facts??tb(a.peerDeviceFacts,Object.fromEntries(Object.entries(s).filter(([,S])=>S.at>a.peerDeviceSnapshotAt))),m=l.filter(S=>S.locality==="remote");let y=a.sessions,_=!1;const b=[],R=new Map;for(let S=0;S<y.length;S+=1)R.set(y[S].session_id,S);for(const S of m){const U=R.get(S.session_id);if(U===void 0){b.push(S);continue}y[U]!==S&&(_||(y=y.slice(),_=!0),y[U]=Wt(y[U],S))}b.length>0&&(y=[...y,...b]);for(const S of l){if(S.locality==="remote"||!u.has(S.session_id))continue;const U=R.get(S.session_id);U===void 0||y[U]===S||(_||(y=y.slice(),_=!0),y[U]=Wt(y[U],S))}const M=new Set(l.map(S=>S.session_id)),G=new Set;for(const S of l)S.locality==="remote"&&typeof S.owner_device=="string"&&S.owner_device!==""&&S.reachable!==!1&&G.add(S.owner_device);const A=new Set;for(const S of y){if(S.locality!=="remote"||typeof S.owner_device!="string"||!h?.removed.includes(S.owner_device))continue;const U=a.placementFacts[S.session_id];U&&U.at>=(i??0)||(A.add(S.session_id),delete d[S.session_id])}for(const[S,U]of Object.entries(a.placementFacts))U.locality==="remote"&&(M.has(S)||U.at>=r||g[U.owner_device]?.reachable!==!1&&(U.owner_device===""||!G.has(U.owner_device)||(A.add(S),delete d[S])));A.size>0&&(y=y.filter(S=>!A.has(S.session_id)));const O=y.map(S=>nb(S,g));return O.some((S,U)=>S!==y[U])&&(y=O,_=!0),!f&&b.length===0&&!_&&A.size===0&&Object.keys(s).length===0&&i===void 0?{}:{sessions:y,placementFacts:d,peerDeviceFacts:g,peerDeviceSnapshotAt:h?.watermark??a.peerDeviceSnapshotAt,forgotten:c,...f?{answerSeq:a.answerSeq+1}:{}}})}}),{name:"canonical-sessions-storage",merge:Bb,partialize:e=>({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}]))})}));function OE(e,t){return t?e.filter(n=>n.archived!==!0):e}function PE(e,t){let n=!1;const r=e.map(s=>{const i=t[s.session_id];return i===void 0||!i.answered||s.archived===i.archived?s:(n=!0,{...s,archived:i.archived})});return n?r:e}function jE(e,t){return`${t?"Unarchive":"Archive"} “${e}”`}function ME(e,t,n){return e!=="sessions.archive"&&e!=="sessions.unarchive"?!0:n?e==="sessions.unarchive"?t===!0:t!==!0:!1}const DE="This backend cannot archive conversations. Update the backend and try again.",NE="This conversation is already archived. Use /unarchive to restore it.",LE="This conversation is not archived, so there is nothing to restore.",$E="This window cannot tell whether that conversation is archived - it is not among the chats listed here. Find it with search and use its row to restore it.";function UE(e,t,n){return n&&e&&t.trim().length>0}function FE(e,t){return t===e}var Sr=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(){}},tn=typeof window>"u"||"Deno"in globalThis;function Qe(){}function Gb(e,t){return typeof e=="function"?e(t):e}function Ui(e){return typeof e=="number"&&e>=0&&e!==1/0}function cu(e,t){return Math.max(e+(t||0)-Date.now(),0)}function vn(e,t){return typeof e=="function"?e(t):e}function it(e,t){return typeof e=="function"?e(t):e}function Bc(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Io(a,t.options))return!1}else if(!hr(t.queryKey,a))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||s&&s!==t.state.fetchStatus||i&&!i(t))}function Gc(e,t){const{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(pr(t.options.mutationKey)!==pr(i))return!1}else if(!hr(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Io(e,t){return(t?.queryKeyHashFn||pr)(e)}function pr(e){return JSON.stringify(e,(t,n)=>Bi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function hr(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>hr(e[n],t[n])):!1}function lu(e,t){if(e===t)return e;const n=Hc(e)&&Hc(t);if(n||Bi(e)&&Bi(t)){const r=n?e:Object.keys(e),s=r.length,i=n?t:Object.keys(t),a=i.length,c=n?[]:{};let l=0;for(let d=0;d<a;d++){const u=n?d:i[d];(!n&&r.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=lu(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return s===a&&l===s?e:c}return t}function Fi(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 Hc(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Bi(e){if(!Wc(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Wc(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Wc(e){return Object.prototype.toString.call(e)==="[object Object]"}function Hb(e){return new Promise(t=>{setTimeout(t,e)})}function Gi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?lu(e,t):t}function BE(e){return e}function Wb(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function zb(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xo=Symbol();function du(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xo?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Zb=class extends Sr{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!tn&&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 Zb,Vb=class extends Sr{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!tn&&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}},ls=new Vb;function Hi(){let e,t;const n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}function Kb(e){return Math.min(1e3*2**e,3e4)}function uu(e){return(e??"online")==="online"?ls.isOnline():!0}var fu=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function di(e){return e instanceof fu}function pu(e){let t=!1,n=0,r=!1,s;const i=Hi(),a=m=>{r||(p(new fu(m)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>To.isFocused()&&(e.networkMode==="always"||ls.isOnline())&&e.canRun(),u=()=>uu(e.networkMode)&&e.canRun(),f=m=>{r||(r=!0,e.onSuccess?.(m),s?.(),i.resolve(m))},p=m=>{r||(r=!0,e.onError?.(m),s?.(),i.reject(m))},h=()=>new Promise(m=>{s=y=>{(r||d())&&m(y)},e.onPause?.()}).then(()=>{s=void 0,r||e.onContinue?.()}),g=()=>{if(r)return;let m;const y=n===0?e.initialPromise:void 0;try{m=y??e.fn()}catch(_){m=Promise.reject(_)}Promise.resolve(m).then(f).catch(_=>{if(r)return;const b=e.retry??(tn?0:3),R=e.retryDelay??Kb,M=typeof R=="function"?R(n,_):R,G=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,_);if(t||!G){p(_);return}n++,e.onFail?.(n,_),Hb(M).then(()=>d()?void 0:h()).then(()=>{t?p(_):g()})})};return{promise:i,cancel:a,continue:()=>(s?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?g():h().then(g),i)}}var Yb=e=>setTimeout(e,0);function Qb(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Yb;const i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var Pe=Qb(),hu=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ui(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(tn?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Jb=class extends hu{#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=Xb(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=Gi(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(Qe).catch(Qe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>it(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xo||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||!cu(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,r=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},s=()=>{const c=du(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(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:s};r(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 a=c=>{di(c)&&c.silent||this.#i({type:"error",error:c}),di(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=pu({initialPromise:t?.initialPromise,fn:i.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){a(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){a(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:a,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,...mu(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 r=e.error;return di(r)&&r.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Pe.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function mu(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:uu(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Xb(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var qb=class extends Sr{constructor(e={}){super(),this.config=e,this.#t=new Map}#t;build(e,t,n){const r=t.queryKey,s=t.queryHash??Io(r,t);let i=this.get(s);return i||(i=new Jb({client:e,queryKey:r,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(i)),i}add(e){this.#t.has(e.queryHash)||(this.#t.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#t.get(e.queryHash);t&&(e.destroy(),t===e&&this.#t.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Pe.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#t.get(e)}getAll(){return[...this.#t.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Bc(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Bc(e,n)):t}notify(e){Pe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Pe.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Pe.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ew=class extends hu{#t;#e;#n;constructor(e){super(),this.mutationId=e.mutationId,this.#e=e.mutationCache,this.#t=[],this.state=e.state||tw(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#e.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#e.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#e.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){this.#n=pu({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(r,s)=>{this.#r({type:"failed",failureCount:r,error:s})},onPause:()=>{this.#r({type:"pause"})},onContinue:()=>{this.#r({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#e.canRun(this)});const t=this.state.status==="pending",n=!this.#n.canStart();try{if(!t){this.#r({type:"pending",variables:e,isPaused:n}),await this.#e.config.onMutate?.(e,this);const s=await this.options.onMutate?.(e);s!==this.state.context&&this.#r({type:"pending",context:s,variables:e,isPaused:n})}const r=await this.#n.start();return await this.#e.config.onSuccess?.(r,e,this.state.context,this),await this.options.onSuccess?.(r,e,this.state.context),await this.#e.config.onSettled?.(r,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(r,null,e,this.state.context),this.#r({type:"success",data:r}),r}catch(r){try{throw await this.#e.config.onError?.(r,e,this.state.context,this),await this.options.onError?.(r,e,this.state.context),await this.#e.config.onSettled?.(void 0,r,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,r,e,this.state.context),r}finally{this.#r({type:"error",error:r})}}finally{this.#e.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Pe.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#e.notify({mutation:this,type:"updated",action:e})})}};function tw(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var nw=class extends Sr{constructor(e={}){super(),this.config=e,this.#t=new Set,this.#e=new Map,this.#n=0}#t;#e;#n;build(e,t,n){const r=new ew({mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#t.add(e);const t=Gr(e);if(typeof t=="string"){const n=this.#e.get(t);n?n.push(e):this.#e.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#t.delete(e)){const t=Gr(e);if(typeof t=="string"){const n=this.#e.get(t);if(n)if(n.length>1){const r=n.indexOf(e);r!==-1&&n.splice(r,1)}else n[0]===e&&this.#e.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Gr(e);if(typeof t=="string"){const r=this.#e.get(t)?.find(s=>s.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Gr(e);return typeof t=="string"?this.#e.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Pe.batch(()=>{this.#t.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#t.clear(),this.#e.clear()})}getAll(){return Array.from(this.#t)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Gc(t,n))}findAll(e={}){return this.getAll().filter(t=>Gc(e,t))}notify(e){Pe.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Pe.batch(()=>Promise.all(e.map(t=>t.continue().catch(Qe))))}};function Gr(e){return e.options.scope?.id}function zc(e){return{onFetch:(t,n)=>{const r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const d=async()=>{let u=!1;const f=g=>{Object.defineProperty(g,"signal",{enumerable:!0,get:()=>(t.signal.aborted?u=!0:t.signal.addEventListener("abort",()=>{u=!0}),t.signal)})},p=du(t.options,t.fetchOptions),h=async(g,m,y)=>{if(u)return Promise.reject();if(m==null&&g.pages.length)return Promise.resolve(g);const _={client:t.client,queryKey:t.queryKey,pageParam:m,direction:y?"backward":"forward",meta:t.options.meta};f(_);const b=await p(_),{maxPages:R}=t.options,M=y?zb:Wb;return{pages:M(g.pages,b,R),pageParams:M(g.pageParams,m,R)}};if(s&&i.length){const g=s==="backward",m=g?gu:Wi,y={pages:i,pageParams:a},_=m(r,y);c=await h(y,_,g)}else{const g=e??i.length;do{const m=l===0?a[0]??r.initialPageParam:Wi(r,c);if(l>0&&m==null)break;c=await h(c,m),l++}while(l<g)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Wi(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function gu(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function GE(e,t){return t?Wi(e,t)!=null:!1}function HE(e,t){return!t||!e.getPreviousPageParam?!1:gu(e,t)!=null}var rw=class{#t;#e;#n;#r;#s;#a;#o;#i;constructor(e={}){this.#t=e.queryCache||new qb,this.#e=e.mutationCache||new nw,this.#n=e.defaultOptions||{},this.#r=new Map,this.#s=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=To.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onFocus())}),this.#i=ls.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#t.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#t.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#e.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#t.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(vn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#t.findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=this.#t.get(r.queryHash)?.state.data,a=Gb(t,i);if(a!==void 0)return this.#t.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Pe.batch(()=>this.#t.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#t.get(t.queryHash)?.state}removeQueries(e){const t=this.#t;Pe.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#t;return Pe.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Pe.batch(()=>this.#t.findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Qe).catch(Qe)}invalidateQueries(e,t={}){return Pe.batch(()=>(this.#t.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Pe.batch(()=>this.#t.findAll(e).filter(s=>!s.isDisabled()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Qe)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Qe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#t.build(this,t);return n.isStaleByTime(vn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Qe).catch(Qe)}fetchInfiniteQuery(e){return e.behavior=zc(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Qe).catch(Qe)}ensureInfiniteQueryData(e){return e.behavior=zc(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return ls.isOnline()?this.#e.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#t}getMutationCache(){return this.#e}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(pr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(r=>{hr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(pr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(r=>{hr(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Io(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===xo&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#t.clear(),this.#e.clear()}},sw=class extends Sr{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=Hi(),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),Zc(this.#e,this.options)?this.#u():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zi(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zi(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 it(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&&!Fi(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const r=this.hasListeners();r&&Vc(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),r&&(this.#e!==n||it(this.options.enabled,this.#e)!==it(t.enabled,this.#e)||vn(this.options.staleTime,this.#e)!==vn(t.staleTime,this.#e))&&this.#g();const s=this.#y();r&&(this.#e!==n||it(this.options.enabled,this.#e)!==it(t.enabled,this.#e)||s!==this.#c)&&this.#_(s)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return ow(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(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(r),t?.(r),e[r])})}),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(Qe)),t}#g(){this.#b();const e=vn(this.options.staleTime,this.#e);if(tn||this.#r.isStale||!Ui(e))return;const n=cu(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}#_(e){this.#w(),this.#c=e,!(tn||it(this.options.enabled,this.#e)===!1||!Ui(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||To.isFocused())&&this.#u()},this.#c))}#v(){this.#g(),this.#_(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,r=this.options,s=this.#r,i=this.#s,a=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const S=this.hasListeners(),U=!S&&Zc(e,t),V=S&&Vc(e,n,t,r);(U||V)&&(u={...u,...mu(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:g,status:m}=u;p=u.data;let y=!1;if(t.placeholderData!==void 0&&p===void 0&&m==="pending"){let S;s?.isPlaceholderData&&t.placeholderData===a?.placeholderData?(S=s.data,y=!0):S=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,S!==void 0&&(m="success",p=Gi(s?.data,S,t),f=!0)}if(t.select&&p!==void 0&&!y)if(s&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Gi(s?.data,p,t),this.#f=p,this.#i=null}catch(S){this.#i=S}this.#i&&(h=this.#i,p=this.#f,g=Date.now(),m="error");const _=u.fetchStatus==="fetching",b=m==="pending",R=m==="error",M=b&&_,G=p!==void 0,O={status:m,fetchStatus:u.fetchStatus,isPending:b,isSuccess:m==="success",isError:R,isInitialLoading:M,isLoading:M,data:p,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:g,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:_,isRefetching:_&&!b,isLoadingError:R&&!G,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:R&&G,isStale:Co(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const S=ce=>{O.status==="error"?ce.reject(O.error):O.data!==void 0&&ce.resolve(O.data)},U=()=>{const ce=this.#o=O.promise=Hi();S(ce)},V=this.#o;switch(V.status){case"pending":e.queryHash===n.queryHash&&S(V);break;case"fulfilled":(O.status==="error"||O.data!==V.value)&&U();break;case"rejected":(O.status!=="error"||O.error!==V.reason)&&U();break}}return O}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),Fi(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#h.size)return!0;const i=new Set(s??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(a=>{const c=a;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.#v()}#k(e){Pe.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function iw(e,t){return it(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Zc(e,t){return iw(e,t)||e.state.data!==void 0&&zi(e,t,t.refetchOnMount)}function zi(e,t,n){if(it(t.enabled,e)!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Co(e,t)}return!1}function Vc(e,t,n,r){return(e!==t||it(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Co(e,n)}function Co(e,t){return it(t.enabled,e)!==!1&&e.isStaleByTime(vn(t.staleTime,e))}function ow(e,t){return!Fi(e.getCurrentResult(),t)}var Ao=v.createContext(void 0),aw=e=>{const t=v.useContext(Ao);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},WE=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),Xu.jsx(Ao.Provider,{value:e,children:t})),yu=v.createContext(!1),cw=()=>v.useContext(yu);yu.Provider;function lw(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var dw=v.createContext(lw()),uw=()=>v.useContext(dw);function fw(e,t){return typeof e=="function"?e(...t):!!e}function Kc(){}var pw=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},hw=e=>{v.useEffect(()=>{e.clearReset()},[e])},mw=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||fw(n,[e.error,r])),gw=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)))},yw=(e,t)=>e.isLoading&&e.isFetching&&!t,_w=(e,t)=>e?.suspense&&t.isPending,Yc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function vw(e,t,n){const r=aw(n),s=cw(),i=uw(),a=r.defaultQueryOptions(e);r.getDefaultOptions().queries?._experimental_beforeQuery?.(a),a._optimisticResults=s?"isRestoring":"optimistic",gw(a),pw(a,i),hw(i);const c=!r.getQueryCache().get(a.queryHash),[l]=v.useState(()=>new t(r,a)),d=l.getOptimisticResult(a),u=!s&&e.subscribed!==!1;if(v.useSyncExternalStore(v.useCallback(f=>{const p=u?l.subscribe(Pe.batchCalls(f)):Kc;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),v.useEffect(()=>{l.setOptions(a)},[a,l]),_w(a,d))throw Yc(a,l,i);if(mw({result:d,errorResetBoundary:i,throwOnError:a.throwOnError,query:r.getQueryCache().get(a.queryHash),suspense:a.suspense}))throw d.error;return r.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!tn&&yw(d,s)&&(c?Yc(a,l,i):r.getQueryCache().get(a.queryHash)?.promise)?.catch(Kc).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function _u(e,t){return vw(e,sw,t)}/**
|
|
41
41
|
* @remix-run/router v1.23.0
|
|
42
42
|
*
|
|
43
43
|
* Copyright (c) Remix Software Inc.
|
|
@@ -46,7 +46,7 @@ ${e}`)}function $i(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
|
|
|
46
46
|
* LICENSE.md file in the root directory of this source tree.
|
|
47
47
|
*
|
|
48
48
|
* @license MIT
|
|
49
|
-
*/function mr(){return mr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},mr.apply(this,arguments)}var At;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(At||(At={}));const Qc="popstate";function
|
|
49
|
+
*/function mr(){return mr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},mr.apply(this,arguments)}var At;(function(e){e.Pop="POP",e.Push="PUSH",e.Replace="REPLACE"})(At||(At={}));const Qc="popstate";function zE(e){e===void 0&&(e={});function t(s,i){let{pathname:a="/",search:c="",hash:l=""}=nn(s.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),Zi("",{pathname:a,search:c,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(s,i){let a=s.document.querySelector("base"),c="";if(a&&a.getAttribute("href")){let l=s.location.href,d=l.indexOf("#");c=d===-1?l:l.slice(0,d)}return c+"#"+(typeof i=="string"?i:vu(i))}function r(s,i){Oo(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return ww(t,n,r,e)}function ke(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Oo(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function bw(){return Math.random().toString(36).substr(2,8)}function Jc(e,t){return{usr:e.state,key:e.key,idx:t}}function Zi(e,t,n,r){return n===void 0&&(n=null),mr({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?nn(t):t,{state:n,key:t&&t.key||r||bw()})}function vu(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function nn(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function ww(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,a=s.history,c=At.Pop,l=null,d=u();d==null&&(d=0,a.replaceState(mr({},a.state,{idx:d}),""));function u(){return(a.state||{idx:null}).idx}function f(){c=At.Pop;let y=u(),_=y==null?null:y-d;d=y,l&&l({action:c,location:m.location,delta:_})}function p(y,_){c=At.Push;let b=Zi(m.location,y,_);n&&n(b,y),d=u()+1;let R=Jc(b,d),M=m.createHref(b);try{a.pushState(R,"",M)}catch(G){if(G instanceof DOMException&&G.name==="DataCloneError")throw G;s.location.assign(M)}i&&l&&l({action:c,location:m.location,delta:1})}function h(y,_){c=At.Replace;let b=Zi(m.location,y,_);n&&n(b,y),d=u();let R=Jc(b,d),M=m.createHref(b);a.replaceState(R,"",M),i&&l&&l({action:c,location:m.location,delta:0})}function g(y){let _=s.location.origin!=="null"?s.location.origin:s.location.href,b=typeof y=="string"?y:vu(y);return b=b.replace(/ $/,"%20"),ke(_,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,_)}let m={get action(){return c},get location(){return e(s,a)},listen(y){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(Qc,f),l=y,()=>{s.removeEventListener(Qc,f),l=null}},createHref(y){return t(s,y)},createURL:g,encodeLocation(y){let _=g(y);return{pathname:_.pathname,search:_.search,hash:_.hash}},push:p,replace:h,go(y){return a.go(y)}};return m}var Xc;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Xc||(Xc={}));function Sw(e,t,n){return n===void 0&&(n="/"),kw(e,t,n)}function kw(e,t,n,r){let s=typeof t=="string"?nn(t):t,i=Su(s.pathname||"/",n);if(i==null)return null;let a=bu(e);Rw(a);let c=null;for(let l=0;c==null&&l<a.length;++l){let d=Nw(i);c=jw(a[l],d)}return c}function bu(e,t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(i,a,c)=>{let l={relativePath:c===void 0?i.path||"":c,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(ke(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let d=jt([r,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(ke(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),bu(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Ow(d,i.index),routesMeta:u})};return e.forEach((i,a)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))s(i,a);else for(let l of wu(i.path))s(i,a,l)}),t}function wu(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let a=wu(r.join("/")),c=[];return c.push(...a.map(l=>l===""?i:[i,l].join("/"))),s&&c.push(...a),c.map(l=>e.startsWith("/")&&l===""?"/":l)}function Rw(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Pw(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Ew=/^:[\w-]+$/,Iw=3,xw=2,Tw=1,Cw=10,Aw=-2,qc=e=>e==="*";function Ow(e,t){let n=e.split("/"),r=n.length;return n.some(qc)&&(r+=Aw),t&&(r+=xw),n.filter(s=>!qc(s)).reduce((s,i)=>s+(Ew.test(i)?Iw:i===""?Tw:Cw),r)}function Pw(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function jw(e,t,n){let{routesMeta:r}=e,s={},i="/",a=[];for(let c=0;c<r.length;++c){let l=r[c],d=c===r.length-1,u=i==="/"?t:t.slice(i.length)||"/",f=Mw({path:l.relativePath,caseSensitive:l.caseSensitive,end:d},u),p=l.route;if(!f)return null;Object.assign(s,f.params),a.push({params:s,pathname:jt([i,f.pathname]),pathnameBase:Fw(jt([i,f.pathnameBase])),route:p}),f.pathnameBase!=="/"&&(i=jt([i,f.pathnameBase]))}return a}function Mw(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Dw(e.path,e.caseSensitive,e.end),s=t.match(n);if(!s)return null;let i=s[0],a=i.replace(/(.)\/+$/,"$1"),c=s.slice(1);return{params:r.reduce((d,u,f)=>{let{paramName:p,isOptional:h}=u;if(p==="*"){let m=c[f]||"";a=i.slice(0,i.length-m.length).replace(/(.)\/+$/,"$1")}const g=c[f];return h&&!g?d[p]=void 0:d[p]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:a,pattern:e}}function Dw(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Oo(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,c,l)=>(r.push({paramName:c,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function Nw(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Oo(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Su(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Lw(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?nn(e):e;return{pathname:n?n.startsWith("/")?n:$w(n,t):t,search:Bw(r),hash:Gw(s)}}function $w(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function ui(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function Uw(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Po(e,t){let n=Uw(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function jo(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=nn(e):(s=mr({},e),ke(!s.pathname||!s.pathname.includes("?"),ui("?","pathname","search",s)),ke(!s.pathname||!s.pathname.includes("#"),ui("#","pathname","hash",s)),ke(!s.search||!s.search.includes("#"),ui("#","search","hash",s)));let i=e===""||s.pathname==="",a=i?"/":s.pathname,c;if(a==null)c=n;else{let f=t.length-1;if(!r&&a.startsWith("..")){let p=a.split("/");for(;p[0]==="..";)p.shift(),f-=1;s.pathname=p.join("/")}c=f>=0?t[f]:"/"}let l=Lw(s,c),d=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(d||u)&&(l.pathname+="/"),l}const jt=e=>e.join("/").replace(/\/\/+/g,"/"),Fw=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Bw=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Gw=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Hw(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const ku=["post","put","patch","delete"];new Set(ku);const Ww=["get",...ku];new Set(Ww);/**
|
|
50
50
|
* React Router v6.30.0
|
|
51
51
|
*
|
|
52
52
|
* Copyright (c) Remix Software Inc.
|
|
@@ -55,4 +55,4 @@ ${e}`)}function $i(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}f
|
|
|
55
55
|
* LICENSE.md file in the root directory of this source tree.
|
|
56
56
|
*
|
|
57
57
|
* @license MIT
|
|
58
|
-
*/function gr(){return gr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},gr.apply(this,arguments)}const Mo=v.createContext(null),zw=v.createContext(null),rn=v.createContext(null),vs=v.createContext(null),Rt=v.createContext({outlet:null,matches:[],isDataRoute:!1}),Ru=v.createContext(null);function zE(e,t){let{relative:n}=t===void 0?{}:t;In()||ke(!1);let{basename:r,navigator:s}=v.useContext(rn),{hash:i,pathname:a,search:c}=Kw(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:jt([r,a])),s.createHref({pathname:l,search:c,hash:i})}function In(){return v.useContext(vs)!=null}function bs(){return In()||ke(!1),v.useContext(vs).location}function Eu(e){v.useContext(rn).static||v.useLayoutEffect(e)}function Zw(){let{isDataRoute:e}=v.useContext(Rt);return e?o0():Vw()}function Vw(){In()||ke(!1);let e=v.useContext(Mo),{basename:t,future:n,navigator:r}=v.useContext(rn),{matches:s}=v.useContext(Rt),{pathname:i}=bs(),a=JSON.stringify(Po(s,n.v7_relativeSplatPath)),c=v.useRef(!1);return Eu(()=>{c.current=!0}),v.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=jo(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:jt([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,i,e])}function ZE(){let{matches:e}=v.useContext(Rt),t=e[e.length-1];return t?t.params:{}}function Kw(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(rn),{matches:s}=v.useContext(Rt),{pathname:i}=bs(),a=JSON.stringify(Po(s,r.v7_relativeSplatPath));return v.useMemo(()=>jo(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function Yw(e,t){return Qw(e,t)}function Qw(e,t,n,r){In()||ke(!1);let{navigator:s,static:i}=v.useContext(rn),{matches:a}=v.useContext(Rt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=bs(),f;if(t){var p;let _=typeof t=="string"?nn(t):t;d==="/"||(p=_.pathname)!=null&&p.startsWith(d)||ke(!1),f=_}else f=u;let h=f.pathname||"/",g=h;if(d!=="/"){let _=d.replace(/^\//,"").split("/");g="/"+h.replace(/^\//,"").split("/").slice(_.length).join("/")}let m=Sw(e,{pathname:g}),y=t0(m&&m.map(_=>Object.assign({},_,{params:Object.assign({},l,_.params),pathname:jt([d,s.encodeLocation?s.encodeLocation(_.pathname).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?d:jt([d,s.encodeLocation?s.encodeLocation(_.pathnameBase).pathname:_.pathnameBase])})),a,n,r);return t&&y?v.createElement(vs.Provider,{value:{location:gr({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:At.Pop}},y):y}function Jw(){let e=i0(),t=Hw(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const Xw=v.createElement(Jw,null);class qw extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(Rt.Provider,{value:this.props.routeContext},v.createElement(Ru.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function e0(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(Mo);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(Rt.Provider,{value:t},r)}function t0(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:h}=n,g=f.route.loader&&p[f.route.id]===void 0&&(!h||h[f.route.id]===void 0);if(f.route.lazy||g){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let h,g=!1,m=null,y=null;n&&(h=c&&f.route.id?c[f.route.id]:void 0,m=f.route.errorElement||Xw,l&&(d<0&&p===0?(a0("route-fallback"),g=!0,y=null):d===p&&(g=!0,y=f.route.hydrateFallbackElement||null)));let _=t.concat(a.slice(0,p+1)),b=()=>{let R;return h?R=m:g?R=y:f.route.Component?R=v.createElement(f.route.Component,null):f.route.element?R=f.route.element:R=u,v.createElement(e0,{match:f,routeContext:{outlet:u,matches:_,isDataRoute:n!=null},children:R})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?v.createElement(qw,{location:n.location,revalidation:n.revalidation,component:m,error:h,children:b(),routeContext:{outlet:null,matches:_,isDataRoute:!0}}):b()},null)}var Iu=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Iu||{}),xu=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(xu||{});function n0(e){let t=v.useContext(Mo);return t||ke(!1),t}function r0(e){let t=v.useContext(zw);return t||ke(!1),t}function s0(e){let t=v.useContext(Rt);return t||ke(!1),t}function Tu(e){let t=s0(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function i0(){var e;let t=v.useContext(Ru),n=r0(),r=Tu();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function o0(){let{router:e}=n0(Iu.UseNavigateStable),t=Tu(xu.UseNavigateStable),n=v.useRef(!1);return Eu(()=>{n.current=!0}),v.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,gr({fromRouteId:t},i)))},[e,t])}const el={};function a0(e,t,n){el[e]||(el[e]=!0)}function VE(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function KE(e){let{to:t,replace:n,state:r,relative:s}=e;In()||ke(!1);let{future:i,static:a}=v.useContext(rn),{matches:c}=v.useContext(Rt),{pathname:l}=bs(),d=Zw(),u=jo(t,Po(c,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return v.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function c0(e){ke(!1)}function YE(e){let{basename:t="/",children:n=null,location:r,navigationType:s=At.Pop,navigator:i,static:a=!1,future:c}=e;In()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=v.useMemo(()=>({basename:l,navigator:i,static:a,future:gr({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof r=="string"&&(r=nn(r));let{pathname:u="/",search:f="",hash:p="",state:h=null,key:g="default"}=r,m=v.useMemo(()=>{let y=Su(u,l);return y==null?null:{location:{pathname:y,search:f,hash:p,state:h,key:g},navigationType:s}},[l,u,f,p,h,g,s]);return m==null?null:v.createElement(rn.Provider,{value:d},v.createElement(vs.Provider,{children:n,value:m}))}function QE(e){let{children:t,location:n}=e;return Yw(Vi(t),n)}new Promise(()=>{});function Vi(e,t){t===void 0&&(t=[]);let n=[];return v.Children.forEach(e,(r,s)=>{if(!v.isValidElement(r))return;let i=[...t,s];if(r.type===v.Fragment){n.push.apply(n,Vi(r.props.children,i));return}r.type!==c0&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Vi(r.props.children,i)),n.push(a)}),n}function JE(e){return e!=="detached"&&e!=="wedged"}function Cu(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function XE(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,r=Cu(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:r};case"detached":return e.reconnecting?{title:r?"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:r}:{title:r?"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:r};default:return null}}function l0(e){if(im(e))return"deadline";const t=e instanceof ye?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Au={unreachable:"",deadline:"",unauthorized:"",outdated:"Update the server and try again.",unknown:""},Ki={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 d0(e,t){const n=l0(t);return[e,Ki[n],Au[n]].filter(Boolean).join(" ")}const Yi={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."},u0={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 qE(e,t){return e!=="unpaired"?null:u0[t??"unpaired"]}function eI(e,t){return e!=="unpaired"?null:Yi[t??"unpaired"]}function tI(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:i=!1}=e;return s==="pre-handshake"?i:s!==null||n?!1:r?i:t==="outdated"}function nI(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:i=null}=e;if(i!==null)return Yi[i];if(!s){if(t==="unreachable")return`${Ki.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`${Ki.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. ${Au.outdated}`}return n?Yi.unpaired:s?`The Local Operator server is missing ${r.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 f0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function rI(e,t=null){return t!==null||!e?!0:f0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function p0(e,t){return t instanceof ye&&t.status===null?!1:e<1}function sI(e,t){return t instanceof ye&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const h0={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 iI(e,t,n){return e===null?{sentence:d0(t,n),remedy:!0}:{sentence:h0[e],remedy:Cu(e)}}const ws=260,Do=220,No=320,Ou=56,Lo=480,oI=8,$o=44,Pu=400,m0=560;function ju(e){return Math.max(0,Math.min(m0,e-Lo))}function tl(e){return ju(e)>=Pu?"docked":"overlay"}function aI({capacity:e,min:t,max:n,drawn:r}){const s=e>=t;return s?{resizable:s,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:s,value:r,minWidth:r,maxWidth:r}}function g0(e,t=ws,n=$o){return tl(e-Mu(t)-n)==="overlay"&&tl(e-Ou-n)==="docked"}function Mu(e){return Number.isNaN(e)?ws:Math.min(No,Math.max(Do,e))}function y0(e,t=$o){return Math.max(0,Math.min(No,e-Lo-t))}function cI(e,t,n=ws,r=!1,s=$o){const i=!t&&r&&g0(e,n,s),a=t||i,c=y0(e,s);return{mode:a?"strip":"docked",width:a?Ou:Math.min(Mu(n),c),collapsed:a,resizable:!a&&c>=Do}}function lI(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const dI=e=>e?"⌘B":"Ctrl+B",_0=()=>{const e=v.useContext(Ao)??null,t=v.useMemo(()=>new rw({defaultOptions:{queries:{enabled:!1,retry:!1}}}),[]);return v.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])},Du={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},v0=3e4,b0=15e3;function w0(e){return e?.desktop_available===!0}function uI(){const{client:e,provided:t}=_0();return _u({enabled:t,queryKey:Du.capabilities,queryFn:async()=>{try{return await xe({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>w0(n.state.data)?v0:b0,refetchIntervalInBackground:!0},e)}function S0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function fI(e,t,n=1){return S0(e,t,n)==="enabled"}function pI(e){return _u({queryKey:Du.providers,queryFn:()=>xe({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:p0})}const k0="data-canvas-shortcuts",R0=`[${k0}]`,E0=e=>Nu(e,R0),I0='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',hI=e=>Nu(e,I0);function Nu(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const mI=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&E0(e.target)?"new-file":null},x0=["active","created"],gI={running:"Running",today:"Today",week:"This week",older:"Older"},T0=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Ss(e){return T0.has(e.status?.code??"")}const C0=new Set(["approval","answer"]);function A0(e){return C0.has(e.status?.code??"")}const O0=24*60*60*1e3,P0=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Uo(e,t){const n=t==="created"?e.created_at:e.updated_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}const j0="last_user_at";function M0(e){const t=e[j0],n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:e.created_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}function D0(e,t,n){if(Ss(e))return"running";const r=Uo(e,n);if(r===null)return"older";const s=P0(t);return r>=s?"today":r>=s-6*O0?"week":"older"}function yI(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[D0(s,t,n)].push(s);return r}function N0(e,t,n){const r=Uo(e,n);if(r===null)return"";const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const i=Math.floor(s/60);if(i<24)return`${i}h`;const a=Math.floor(i/24);if(a<7)return`${a}d`;const c=Math.floor(a/7);return a<365?`${c}w`:`${Math.floor(a/365)}y`}function _I(e,t,n){const r=N0(e,t,n);if(!r)return"";const s=n==="created"?"created":"last active";if(r==="now")return`${s} just now`;const i={m:"minute",h:"hour",d:"day",w:"week",y:"year"},a=Number.parseInt(r,10),c=i[r.slice(-1)];return`${s} ${a} ${c}${a===1?"":"s"} ago`}const Qi=["pinned","running","today","week","older","agents","teams"];function vI(e){return e==="agents"||e==="teams"}const yr=8;function L0(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function bI(e,t){return{...e,[t]:(e[t]??yr)+yr}}function wI(e,t,n,r,s){const i=!(e[n]??r);return{expanded:{...e,[n]:i},caps:!i&&!s?L0(t,n):t}}function SI(e,t,n,r){return(e||t!=="")&&(r>yr||n.trim()!=="")}const kI="Collapse, then reopen, to restore the compact list";function RI(e){return(e??yr)>yr}const EI=e=>`section-grown-hint-${e}`,$0=e=>e===1?"Show 1 more":`Show ${e} more`;function II(e,t){return`${$0(e)} ${t}`}const pn={hidden:[],order:[...Qi],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},U0=10,$n=[25,50],F0=50,B0=500,G0=64;function bn(e){const t=Math.max(0,Math.floor(e));return t===0?U0:t<=$n.length?$n[t-1]:$n[$n.length-1]+(t-$n.length)*F0}function xI(e,t){const n=bn(e+1)-bn(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function TI(e,t,n){const r=bn(t+1)-bn(t),s=bn(t),i=Math.min(s+r,e.length);let a=0;for(let l=s;l<i;l+=1)Fo(e[l])&&(a+=1);const c=Math.max(0,i-s-a);return c>0?c:Math.max(0,Math.min(r,n))}function Fo(e){return Ss(e)}function H0(e){return A0(e)?0:Ss(e)?1:2}function W0(e,t){return Ss(e)?M0(e):Uo(e,t)}function z0(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function CI(e,t,n){const r=e.map((s,i)=>({row:s,index:i,lane:t==="active-first"?H0(s):0,at:W0(s,n)}));return r.sort((s,i)=>s.lane-i.lane||z0(s.at,i.at)||s.index-i.index),r.map(s=>s.row)}function AI(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}Fo(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!r)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function OI(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=bn(t.loads),r=[];let s=n;for(const l of e){if(Fo(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function PI(e){if(e.add<=0)return null;const t=e.add===1?"Show 1 more chat":`Show ${e.add} more chats`;if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n} shown`}}const Z0="mt-4",V0="mt-2";function jI(e){return e?Z0:V0}function MI(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function DI(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(i),n.set(c,l)}const r=[...n.values()],s=r.findIndex(i=>i.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function K0(e,t){return!e.hidden.includes(t)}function Lu(e){return e.order.filter(t=>K0(e,t))}function NI(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function LI(e,t,n){const r=Lu(e),s=r.indexOf(t),i=r[s+n];if(s<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const Y0=["running","today","week","older"];function nl(e){return Y0.includes(e)}function $I(e,t,n,r){if(!nl(t)||r&&!r(t))return!1;const s=Lu(e),i=s.indexOf(t);if(i<0)return!1;const a=s[i+n];return a===void 0||!nl(a)?!1:r?r(a):!0}const Q0=["section","agent","flat"],J0=["active-first","recent"];function UI(e){if(typeof e!="object"||e===null)return pn;const t=e,n=new Set(Qi),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of Qi)r.includes(p)||r.push(p);const s=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(s.includes(p)||s.push(p));const i=Q0.includes(t.groupBy)?t.groupBy:pn.groupBy,a=x0.includes(t.basis)?t.basis:pn.basis,c=J0.includes(t.orderBy)?t.orderBy:pn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(B0,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=G0)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:s,order:r,groupBy:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:pn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const $u={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},X0=["recent","name","kind","modified","created","size"],q0=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Bo(e){const t=e&&typeof e=="object"?e:{};return{sort:X0.includes(t.sort??"")?t.sort:$u.sort,order:t.order==="desc"?"desc":"asc",group:typeof t.group=="boolean"?t.group:!0,workingOpen:t.workingOpen===!0,closedSections:Array.isArray(t.closedSections)?[...new Set(t.closedSections.filter(n=>["Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>q0.includes(n)))]:[]}}function FI(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,s)=>{const i=n(r),a=n(s);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const eS=e=>{switch(e.row.kind){case"images":return"Images";case"video":return"Videos";case"audio":return"Sounds";case"spreadsheets":return"Spreadsheets";case"documents":case"presentations":case"code":return"Documents";default:return"Other"}};function BI(e,t,n,r){const s=e.filter(c=>c.highlighted),i=e.filter(c=>!c.highlighted),a=[];if(s.length&&a.push({id:"Highlights",label:"Highlights",items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&i.length&&(a.push({id:"Working files",label:"Working files",items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return a;if(!t.group)i.length&&a.push({id:"Files",label:"Files",items:i,open:!0,highlights:!1});else for(const c of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const l=i.filter(d=>eS(d)===c);l.length&&a.push({id:c,label:c,items:l,open:n||!r.has(c),highlights:!1})}return a}const tS=32,GI=4;function HI(e,t,n){const r=[],s=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,p,h=1)=>{p.forEach((g,m)=>s.set(g.row.document.id,{band:r.length,column:m})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:h}),c+=f};for(const d of e)if(l(d,"header",tS,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(n&&d.id==="Images"){const u=(i-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((i-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:s}}function WI(e,t,n,r){const s=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-s?i=d+1:a=d}const c=new Set;for(let d=i;d<e.bands.length&&e.bands[d].top<=t+n+s;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function zI(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const i=e.bands[s.band],a=e.bands.filter(u=>u.section.id===i.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return i.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.top+(n.startsWith("Page")?r*c:c);let d=s.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(s.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const nS="both",Uu="by-turn",Ji=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function ZI(e){for(const t of Ji)if(e===t.value)return t.value;return Uu}function VI(e){return Ji.find(t=>t.value===e)?.label??Ji[0].label}const KI="primary+alt+shift+space",rS=/^f([1-9]|1[0-9]|2[0-4])$/;function sS(e){return rS.test(e)}function iS(e,t){const n=oS(e,t);return t==="mac"?n.join(""):n.join("+")}function oS(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},s={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 r?r[i]:i in s?s[i]:sS(i)||i.length===1?i.toUpperCase():i)}const ks=[{id:"panel.console",label:"Open console",category:"Panels",defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",label:"Open canvas",category:"Panels",defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",label:"Open run details",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.ask",label:"Open asks",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.browser",label:"Open browser",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.code",label:"Open code review",category:"Panels",defaultChord:null,scope:"app"}],aS=new Map(ks.map(e=>[e.id,e])),cS=e=>aS.get(e),lS=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]),Go=new Map([["primary+p","Reserved: opens the command palette from anywhere."],["primary+shift+p","Reserved: opens the command palette on commands."],["primary+shift+s","Reserved: starts speech to text."],["primary+k","Reserved: opens the command palette on chats."],["primary+n","Reserved: starts a new chat."],["primary+b","Reserved: toggles the sidebar."],["primary+[","Reserved: goes back in the browser, or between chats outside it."],["primary+]","Reserved: goes forward in the browser, or between chats outside it."],["primary+f","Reserved: finds in the browser page, or searches the transcript outside it."],["primary+alt+up","Reserved: walks up the chat regions."],["primary+alt+down","Reserved: walks down the chat regions."],["primary+shift+a","Reserved: archives the focused conversation."],["primary+shift+l","Reserved: opens the focused conversation's tags."],["primary+s","Reserved: saves the canvas document."],["primary+o","Reserved: opens a file in the canvas."],["primary+shift+up","Reserved: moves the focused chat up the pinned order."],["primary+shift+down","Reserved: moves the focused chat down the pinned order."],["primary+c","Reserved: copy."],["primary+x","Reserved: cut."],["primary+v","Reserved: paste."],["primary+a","Reserved: select all."],["primary+z","Reserved: undo."],["primary+shift+z","Reserved: redo."],["primary+y","Reserved: redo on Windows and Linux."],["primary+r","Reserved: reloads the browser page."],["primary+shift+r","Reserved: reloads the browser page, ignoring the cache."],["primary+t","Reserved: opens a new browser tab."],["primary+shift+t","Reserved: reopens the last closed browser tab."],["primary+l","Reserved: focuses the browser address bar."],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?"Reserved: switches to the last browser tab.":`Reserved: switches to browser tab ${e}.`]),["primary+0","Reserved: resets browser page zoom, or app zoom outside it."],["primary+plus","Reserved: zooms the browser page or app in."],["primary+=","Reserved: zooms the browser page or app in."],["primary+-","Reserved: zooms the browser page or app out."],["primary+q","Reserved: quits the app."],["primary+w","Reserved: closes the browser tab, or the window outside it."],["primary+m","Reserved: minimises the window."]]),dS=["primary","alt","shift"],uS={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},fS=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),pS=e=>fS.has(e)||/^[a-z0-9]$/.test(e);function Ho(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!pS(n))return null;const r=new Set;for(const i of t.slice(0,-1)){const a=uS[i];if(a===void 0)return null;r.add(a)}return[...dS.filter(i=>r.has(i)),n].join("+")}const Fu=e=>e.split("+").includes("primary");function Rs(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Go.has(n)?n:cS(e)?.defaultChord??null}function YI(e){const t=new Map;for(const n of ks){const r=Rs(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const hS=e=>e==="mac"?"A shortcut needs ⌘ or Ctrl.":"A shortcut needs Ctrl.";function mS(e,t,n,r="linux"){const s=e===null?null:Ho(e);if(s===null)return"That key cannot be bound.";if(!Fu(s))return hS(r);const i=Go.get(s);if(i!==void 0)return i;for(const a of ks)if(a.id!==t&&Rs(a.id,n)===s)return`Already assigned to ${a.label}.`;return null}function gS(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of ks){const i=t[s.id];if(i===null){r[s.id]=null;continue}const a=typeof i=="string"?Ho(i):null,c=a!==null&&lS.has(a),l=a!==null&&Fu(a)&&(c||!Go.has(a)&&!n.has(a))?a:null;l!==null&&(r[s.id]=l);const d=Rs(s.id,r);d!==null&&n.add(d)}return r}function QI(e,t,n){const r=Rs(e,t);return r===null?null:Bu(r,n)}function Bu(e,t){return iS(e,t)}function JI(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:Bu(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const rl=64,Xi=["canvas","run","browser","console","code"],yS={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Gu(e){return typeof e=="string"&&Xi.includes(e)}function Wo(e){return e.startsWith("draft:")}function kr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function zo(e){return e.length>rl?e.slice(e.length-rl):e}function Hu(e,t,n){return zo([...e.filter(([r])=>r!==t),[t,n]])}function _S(e,t,n){return kr(e,t)!==n?e:e.filter(([r])=>r!==t)}function vS(e,t){return kr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function bS(e,t,n){const r=kr(e,t);return r===void 0?e:zo([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const sl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function il(e,t,n){if(n||typeof t!="string")return sl;const r=kr(e,t);return r===void 0?sl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function wS(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,s]=n;typeof r!="string"||r===""||Wo(r)||Gu(s)&&(t.delete(r),t.set(r,s))}return zo([...t.entries()])}function XI(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function ol(e){return yS[e]}const SS={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Rr=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Es=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,kS=e=>{const t=Rr(e);return t===null||t==="ask"?null:SS[t]},Ct=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Gt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Hu(e.rightSlotMemory,n,t)}},Un=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=_S(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},RS=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=vS(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},ES=Object.freeze({mounted:!1,session:!1}),Wu=Object.freeze([]);function qI(e,t){const n=Rr(t);if(n===null||!Es(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Math.max(Pu,t.rightSlotWidth||Fn);break;case"run":r=Math.max(cl,t.rightSlotWidth||Fn);break;case"browser":r=Math.max(CS,t.rightSlotWidth||Fn);break;case"console":r=Math.max(AS,t.rightSlotWidth||Fn);break;case"code":r=Math.max(cl,t.rightSlotWidth||Fn);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ju(e)):Math.min(r,Math.max(0,e-Lo))}function ex(e){const t=Rr(e);return t!==null&&Es(t,e)}function tx(e){const t=Rr(e);return t!==null&&Es(t,e)?t:null}function nx(e){const t=Rr(e);return(t==="canvas"||t==="ask")&&Es(t,e)}const Fn=640,al=ws,IS=20,xS=4,TS=20,cl=320,CS=480,AS=480,OS=5e3,rx=(e,t)=>e.some(n=>n.surface===t),sx=(e,t=Date.now())=>e.some(n=>t-n.at<OS),PS=[],jS=4,MS=["chatMeasureWidth"],ix=vr()(hs((e,t)=>({finderFiles:$u,setFinderFiles:n=>e({finderFiles:Bo({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Uu,themeName:qu,rightSlotWidth:0,chatSidebarWidth:al,chatSidebarRegions:nS,chatSidebarView:pn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Wu,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:ES,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:PS,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setTheme:n=>{e({themeName:n})},setCanvasOpen:n=>{e(r=>n?{...Ct("isCanvasOpen"),...Gt(r,"canvas")}:{isCanvasOpen:!1,...Un(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...Ct("isRunPanelOpen"),...Gt(r,"run")}:{isRunPanelOpen:!1,...Un(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...Ct("isBrowserPaneOpen"),...Gt(r,"browser")}:{isBrowserPaneOpen:!1,...Un(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...Ct("isConsolePaneOpen"),...Gt(r,"console")}:{isConsolePaneOpen:!1,...Un(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...Ct("isCodeReviewPaneOpen"),...Gt(r,"code")}:{isCodeReviewPaneOpen:!1,...Un(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...Ct("isCodeReviewPaneOpen"),...Gt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...Ct("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:kS(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?s?.dismissSlot?{...c,...RS(i)}:{...c,...il(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(s=>{if(n===null||r<=0)return s.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const i=s.consoleLiveSurface;return i?.sessionId===n&&i.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(i=>i.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const i=s.consoleUnseen.filter(a=>!r.includes(a.surface));return i.length===s.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let i=s.rightSlotMemory,a=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=bS(i,c,n)),n===null||(Wo(n)?a=null:a!==null&&kr(i,n)===void 0&&(i=Hu(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...il(i,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r)=>{if(r===null){e(i=>{const a={...i.shortcutBindings};return delete a[n],{shortcutBindings:a}});return}const s=Ho(r);s!==null&&mS(s,n,t().shortcutBindings)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...Ct("isRunPanelOpen"),...Gt(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(No,Math.max(Do,n))})},setChatSidebarRegions:n=>{e({chatSidebarRegions:n})},setChatSidebarListHeight:n=>{e({chatSidebarListHeight:n})},restoreDefaultChatSidebarListHeight:()=>{e({chatSidebarListHeight:null})},setChatSidebarOrder:n=>{e({chatSidebarOrder:n})},setChatSidebarView:n=>{e({chatSidebarView:n})},dismissBuiltinOffer:n=>{e({dismissedBuiltinOfferSignature:n})},restoreDefaultChatSidebarWidth:()=>{e({chatSidebarWidth:al})},rememberMention:(n,r)=>{e(s=>{const i=s.mentionRecents,a=i?.cwd===n?i.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,IS);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:DS(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=$S(r.conversationRecents),i=NS(s,n);return i.length===s.length&&i.every((a,c)=>a===s[c])?r:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:jS,migrate:GS,partialize:US,merge:BS}));function DS(e,t){return[t,...e.filter(n=>n!==t)].slice(0,xS)}function NS(e,t){return[t,...e.filter(n=>n!==t)].slice(0,TS)}const LS=[];function $S(e){return Array.isArray(e)?e:LS}function US(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:i,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:h,isCodeReviewPaneOpen:g,rightSlotKey:m,...y}=e;return{...y,rightSlotMemory:FS(e.rightSlotMemory)}}function FS(e){return(e??Wu).filter(([t])=>!Wo(t))}function BS(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Bo(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:wS(n.rightSlotMemory),rightSlotLegacySeed:Gu(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:gS(n.shortcutBindings)}}function GS(e,t){const n={...e??{}};if(t<1&&HS(n),t<2)for(const r of MS)delete n[r];if(t<3){let r=null;for(const s of Xi)if(n[ol(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Xi)delete n[ol(s)]}return t<4&&(n.finderFiles=Bo(n.finderFiles)),n}function HS(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const i=e[r];if(typeof i=="number"&&i>0&&i!==s){n=i;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const qi=e=>e.replace(/\\/g,"/"),ox=()=>window.location.hash?qi(window.location.hash.substring(1)):qi(window.location.pathname),ax=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},cx=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const s=n[0]==="~"||n[0]==="",i=s?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=g=>{const m=t-g.length-(g?3:2);let y=[];for(let _=a.length-1;_>=0;_-=1){const b=[a[_],...y];if(b.join("/").length>m)break;y=b}return y},l=(g,m)=>g?`${g}/…/${m.join("/")}`:`…/${m.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=s?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const h=t-(f?`${f}/…/`.length:2);return h>0?l(f,[r.slice(-h)]):"…"},lx=(e,t)=>qi(e).includes(t);export{hs as $,Zw as A,ZE as B,yE as C,ye as D,Zd as E,fE as F,Vd as G,pE as H,gE as I,uE as J,mE as K,S0 as L,ox as M,KE as N,tu as O,Pa as P,AE as Q,hE as R,Fe as S,OE as T,Yd as U,bs as V,hI as W,$S as X,vr as Y,nE as Z,l0 as _,uI as a,kl as a$,Du as a0,zp as a1,sw as a2,zc as a3,GE as a4,BE as a5,vw as a6,sI as a7,_k as a8,th as a9,uw as aA,gw as aB,pw as aC,hw as aD,Kc as aE,_w as aF,Yc as aG,yw as aH,mw as aI,lx as aJ,VS as aK,ZS as aL,zS as aM,KS as aN,_p as aO,st as aP,Yn as aQ,tm as aR,tx as aS,QI as aT,Je as aU,qR as aV,$t as aW,ma as aX,no as aY,ah as aZ,fs as a_,nh as aa,$a as ab,qS as ac,XS as ad,YS as ae,MR as af,TR as ag,AR as ah,OR as ai,$d as aj,ks as ak,Rs as al,Bu as am,mS as an,og as ao,bb as ap,iI as aq,Ji as ar,ZI as as,UE as at,Cb as au,Tb as av,Sr as aw,Pe as ax,lu as ay,cw as az,eI as b,II as b$,Jv as b0,dE as b1,X as b2,fn as b3,lE as b4,Mi as b5,Di as b6,aE as b7,cE as b8,rE as b9,vI as bA,NI as bB,LI as bC,$I as bD,bE,_E as bF,nu as bG,$E as bH,UI as bI,CI as bJ,AI as bK,bn as bL,pn as bM,yI as bN,Lu as bO,SI as bP,MI as bQ,yr as bR,jI as bS,DI as bT,xI as bU,TI as bV,$c as bW,RI as bX,kI as bY,EI as bZ,$0 as b_,sE as ba,iE as bb,JI as bc,sx as bd,OS as be,rx as bf,f0 as bg,rI as bh,nI as bi,tI as bj,Al as bk,pk as bl,ok as bm,Ol as bn,qi as bo,im as bp,Sp as bq,FE as br,kp as bs,Uo as bt,lk as bu,Dc as bv,hk as bw,vb as bx,K0 as by,nl as bz,fI as c,Dv as c$,bI as c0,OI as c1,PI as c2,N0 as c3,vE as c4,Ss as c5,_I as c6,PE as c7,gI as c8,wI as c9,CS as cA,AS as cB,tl as cC,Lo as cD,xm as cE,ER as cF,IR as cG,ME as cH,jE as cI,DE as cJ,LE as cK,NE as cL,wk as cM,wr as cN,Cu as cO,qE as cP,Eo as cQ,eE as cR,DR as cS,qd as cT,pb as cU,_s as cV,xE as cW,TE as cX,Dm as cY,tE as cZ,$R as c_,FI as ca,BI as cb,HI as cc,WI as cd,tS as ce,GI as cf,zI as cg,QS as ch,mI as ci,ax as cj,cx as ck,VI as cl,XE as cm,B_ as cn,bk as co,ex as cp,ES as cq,qI as cr,aI as cs,oI as ct,Pu as cu,ju as cv,fk as cw,uk as cx,cl as cy,Fn as cz,xe as d,L_ as d$,ob as d0,Xd as d1,sb as d2,Mc as d3,wE as d4,E0 as d5,IE as d6,oE as d7,nk as d8,rk as d9,WE as dA,VE as dB,YE as dC,gk as dD,vk as dE,Ve as dF,yb as dG,_0 as dH,Cl as dI,nx as dJ,lI as dK,$o as dL,cI as dM,Ou as dN,y0 as dO,Do as dP,sk as dQ,va as dR,Uh as dS,ik as dT,xp as dU,zR as dV,ZR as dW,ek as dX,tk as dY,WR as dZ,Ud as d_,yk as da,o as db,YI as dc,Ut as dd,Qt as de,gi as df,dI as dg,QE as dh,c0 as di,Mu as dj,Jb as dk,iS as dl,HE as dm,Wo as dn,XI as dp,Bg as dq,Fi as dr,pr as ds,tw as dt,fw as du,rn as dv,Su as dw,zE as dx,Kw as dy,vu as dz,pI as e,zk as e$,hd as e0,Uu as e1,Ql as e2,Gh as e3,ak as e4,xR as e5,CR as e6,LR as e7,NR as e8,PR as e9,yR as eA,cy as eB,Vs as eC,mR as eD,fy as eE,dR as eF,tR as eG,cR as eH,bR as eI,eR as eJ,lR as eK,fR as eL,SR as eM,wR as eN,uR as eO,nR as eP,rR as eQ,sR as eR,iR as eS,oR as eT,aR as eU,vR as eV,Rp as eW,Ep as eX,Ip as eY,Tm as eZ,Bl as e_,mn as ea,dk as eb,mk as ec,ck as ed,Ll as ee,en as ef,Ot as eg,Xk as eh,qk as ei,Qk as ej,Yk as ek,Hk as el,Jl as em,Vk as en,$k as eo,Uk as ep,Bk as eq,kR as er,Fm as es,Kk as et,uy as eu,gR as ev,cd as ew,_R as ex,pR as ey,hR as ez,d0 as f,Yl as f0,Zl as f1,jk as f2,wa as f3,Ho as f4,sS as f5,Gk as f6,bg as f7,Zk as f8,Jk as f9,FR as fA,lr as fB,ao as fC,ym as fD,_m as fE,bp as fF,Rk as fG,Ik as fH,Ya as fI,kk as fJ,Sk as fK,Ek as fL,Il as fM,xk as fN,Tk as fO,RE as fP,UR as fQ,HR as fR,BR as fS,GR as fT,SE as fU,kE as fV,Ck as fW,hp as fX,ba as fY,Wk as fa,kg as fb,Ok as fc,Vm as fd,Mk as fe,Dk as ff,Lk as fg,Nk as fh,Fk as fi,RR as fj,YR as fk,VR as fl,Q_ as fm,JR as fn,KR as fo,QR as fp,XR as fq,Ak as fr,Pk as fs,ps as ft,to as fu,vi as fv,Pp as fw,rw as fx,jR as fy,Xs as fz,ro as g,_u as h,Bp as i,Gp as j,Hp as k,Wp as l,KI as m,JE as n,Eb as o,JS as p,ze as q,p0 as r,EE as s,CE as t,aw as u,db as v,cb as w,ix as x,Ne as y,oS as z};
|
|
58
|
+
*/function gr(){return gr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},gr.apply(this,arguments)}const Mo=v.createContext(null),zw=v.createContext(null),rn=v.createContext(null),vs=v.createContext(null),Rt=v.createContext({outlet:null,matches:[],isDataRoute:!1}),Ru=v.createContext(null);function ZE(e,t){let{relative:n}=t===void 0?{}:t;In()||ke(!1);let{basename:r,navigator:s}=v.useContext(rn),{hash:i,pathname:a,search:c}=Kw(e,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:jt([r,a])),s.createHref({pathname:l,search:c,hash:i})}function In(){return v.useContext(vs)!=null}function bs(){return In()||ke(!1),v.useContext(vs).location}function Eu(e){v.useContext(rn).static||v.useLayoutEffect(e)}function Zw(){let{isDataRoute:e}=v.useContext(Rt);return e?o0():Vw()}function Vw(){In()||ke(!1);let e=v.useContext(Mo),{basename:t,future:n,navigator:r}=v.useContext(rn),{matches:s}=v.useContext(Rt),{pathname:i}=bs(),a=JSON.stringify(Po(s,n.v7_relativeSplatPath)),c=v.useRef(!1);return Eu(()=>{c.current=!0}),v.useCallback(function(d,u){if(u===void 0&&(u={}),!c.current)return;if(typeof d=="number"){r.go(d);return}let f=jo(d,JSON.parse(a),i,u.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:jt([t,f.pathname])),(u.replace?r.replace:r.push)(f,u.state,u)},[t,r,a,i,e])}function VE(){let{matches:e}=v.useContext(Rt),t=e[e.length-1];return t?t.params:{}}function Kw(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=v.useContext(rn),{matches:s}=v.useContext(Rt),{pathname:i}=bs(),a=JSON.stringify(Po(s,r.v7_relativeSplatPath));return v.useMemo(()=>jo(e,JSON.parse(a),i,n==="path"),[e,a,i,n])}function Yw(e,t){return Qw(e,t)}function Qw(e,t,n,r){In()||ke(!1);let{navigator:s,static:i}=v.useContext(rn),{matches:a}=v.useContext(Rt),c=a[a.length-1],l=c?c.params:{};c&&c.pathname;let d=c?c.pathnameBase:"/";c&&c.route;let u=bs(),f;if(t){var p;let _=typeof t=="string"?nn(t):t;d==="/"||(p=_.pathname)!=null&&p.startsWith(d)||ke(!1),f=_}else f=u;let h=f.pathname||"/",g=h;if(d!=="/"){let _=d.replace(/^\//,"").split("/");g="/"+h.replace(/^\//,"").split("/").slice(_.length).join("/")}let m=Sw(e,{pathname:g}),y=t0(m&&m.map(_=>Object.assign({},_,{params:Object.assign({},l,_.params),pathname:jt([d,s.encodeLocation?s.encodeLocation(_.pathname).pathname:_.pathname]),pathnameBase:_.pathnameBase==="/"?d:jt([d,s.encodeLocation?s.encodeLocation(_.pathnameBase).pathname:_.pathnameBase])})),a,n,r);return t&&y?v.createElement(vs.Provider,{value:{location:gr({pathname:"/",search:"",hash:"",state:null,key:"default"},f),navigationType:At.Pop}},y):y}function Jw(){let e=i0(),t=Hw(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return v.createElement(v.Fragment,null,v.createElement("h2",null,"Unexpected Application Error!"),v.createElement("h3",{style:{fontStyle:"italic"}},t),n?v.createElement("pre",{style:s},n):null,null)}const Xw=v.createElement(Jw,null);class qw extends v.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?v.createElement(Rt.Provider,{value:this.props.routeContext},v.createElement(Ru.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function e0(e){let{routeContext:t,match:n,children:r}=e,s=v.useContext(Mo);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),v.createElement(Rt.Provider,{value:t},r)}function t0(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let a=e,c=(s=n)==null?void 0:s.errors;if(c!=null){let u=a.findIndex(f=>f.route.id&&c?.[f.route.id]!==void 0);u>=0||ke(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let f=a[u];if((f.route.HydrateFallback||f.route.hydrateFallbackElement)&&(d=u),f.route.id){let{loaderData:p,errors:h}=n,g=f.route.loader&&p[f.route.id]===void 0&&(!h||h[f.route.id]===void 0);if(f.route.lazy||g){l=!0,d>=0?a=a.slice(0,d+1):a=[a[0]];break}}}return a.reduceRight((u,f,p)=>{let h,g=!1,m=null,y=null;n&&(h=c&&f.route.id?c[f.route.id]:void 0,m=f.route.errorElement||Xw,l&&(d<0&&p===0?(a0("route-fallback"),g=!0,y=null):d===p&&(g=!0,y=f.route.hydrateFallbackElement||null)));let _=t.concat(a.slice(0,p+1)),b=()=>{let R;return h?R=m:g?R=y:f.route.Component?R=v.createElement(f.route.Component,null):f.route.element?R=f.route.element:R=u,v.createElement(e0,{match:f,routeContext:{outlet:u,matches:_,isDataRoute:n!=null},children:R})};return n&&(f.route.ErrorBoundary||f.route.errorElement||p===0)?v.createElement(qw,{location:n.location,revalidation:n.revalidation,component:m,error:h,children:b(),routeContext:{outlet:null,matches:_,isDataRoute:!0}}):b()},null)}var Iu=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Iu||{}),xu=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(xu||{});function n0(e){let t=v.useContext(Mo);return t||ke(!1),t}function r0(e){let t=v.useContext(zw);return t||ke(!1),t}function s0(e){let t=v.useContext(Rt);return t||ke(!1),t}function Tu(e){let t=s0(),n=t.matches[t.matches.length-1];return n.route.id||ke(!1),n.route.id}function i0(){var e;let t=v.useContext(Ru),n=r0(),r=Tu();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function o0(){let{router:e}=n0(Iu.UseNavigateStable),t=Tu(xu.UseNavigateStable),n=v.useRef(!1);return Eu(()=>{n.current=!0}),v.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,gr({fromRouteId:t},i)))},[e,t])}const el={};function a0(e,t,n){el[e]||(el[e]=!0)}function KE(e,t){e?.v7_startTransition,e?.v7_relativeSplatPath}function YE(e){let{to:t,replace:n,state:r,relative:s}=e;In()||ke(!1);let{future:i,static:a}=v.useContext(rn),{matches:c}=v.useContext(Rt),{pathname:l}=bs(),d=Zw(),u=jo(t,Po(c,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(u);return v.useEffect(()=>d(JSON.parse(f),{replace:n,state:r,relative:s}),[d,f,s,n,r]),null}function c0(e){ke(!1)}function QE(e){let{basename:t="/",children:n=null,location:r,navigationType:s=At.Pop,navigator:i,static:a=!1,future:c}=e;In()&&ke(!1);let l=t.replace(/^\/*/,"/"),d=v.useMemo(()=>({basename:l,navigator:i,static:a,future:gr({v7_relativeSplatPath:!1},c)}),[l,c,i,a]);typeof r=="string"&&(r=nn(r));let{pathname:u="/",search:f="",hash:p="",state:h=null,key:g="default"}=r,m=v.useMemo(()=>{let y=Su(u,l);return y==null?null:{location:{pathname:y,search:f,hash:p,state:h,key:g},navigationType:s}},[l,u,f,p,h,g,s]);return m==null?null:v.createElement(rn.Provider,{value:d},v.createElement(vs.Provider,{children:n,value:m}))}function JE(e){let{children:t,location:n}=e;return Yw(Vi(t),n)}new Promise(()=>{});function Vi(e,t){t===void 0&&(t=[]);let n=[];return v.Children.forEach(e,(r,s)=>{if(!v.isValidElement(r))return;let i=[...t,s];if(r.type===v.Fragment){n.push.apply(n,Vi(r.props.children,i));return}r.type!==c0&&ke(!1),!r.props.index||!r.props.children||ke(!1);let a={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=Vi(r.props.children,i)),n.push(a)}),n}function XE(e){return e!=="detached"&&e!=="wedged"}function Cu(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function qE(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,r=Cu(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:r};case"detached":return e.reconnecting?{title:r?"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:r}:{title:r?"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:r};default:return null}}function l0(e){if(im(e))return"deadline";const t=e instanceof ye?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Au={unreachable:"",deadline:"",unauthorized:"",outdated:"Update the server and try again.",unknown:""},Ki={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 d0(e,t){const n=l0(t);return[e,Ki[n],Au[n]].filter(Boolean).join(" ")}const Yi={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."},u0={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 eI(e,t){return e!=="unpaired"?null:u0[t??"unpaired"]}function tI(e,t){return e!=="unpaired"?null:Yi[t??"unpaired"]}function nI(e){const{kind:t,unpaired:n,answered:r,cause:s=null,servedByThisApp:i=!1}=e;return s==="pre-handshake"?i:s!==null||n?!1:r?i:t==="outdated"}function rI(e){const{kind:t,unpaired:n,missing:r,answered:s,cause:i=null}=e;if(i!==null)return Yi[i];if(!s){if(t==="unreachable")return`${Ki.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`${Ki.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. ${Au.outdated}`}return n?Yi.unpaired:s?`The Local Operator server is missing ${r.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 f0=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function sI(e,t=null){return t!==null||!e?!0:f0.filter(r=>(e.features?.[r]??0)<1).length>0||e.desktop_available!==!0}function p0(e,t){return t instanceof ye&&t.status===null?!1:e<1}function iI(e,t){return t instanceof ye&&t.status!==null&&t.status>=400&&t.status<500&&t.status!==408&&t.status!==425&&t.status!==429?!1:e<1}const h0={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 oI(e,t,n){return e===null?{sentence:d0(t,n),remedy:!0}:{sentence:h0[e],remedy:Cu(e)}}const ws=260,Do=220,No=320,Ou=56,Lo=480,aI=8,$o=44,Pu=400,m0=560;function ju(e){return Math.max(0,Math.min(m0,e-Lo))}function tl(e){return ju(e)>=Pu?"docked":"overlay"}function cI({capacity:e,min:t,max:n,drawn:r}){const s=e>=t;return s?{resizable:s,value:Math.min(Math.max(r,t),e),minWidth:t,maxWidth:Math.min(n,e)}:{resizable:s,value:r,minWidth:r,maxWidth:r}}function g0(e,t=ws,n=$o){return tl(e-Mu(t)-n)==="overlay"&&tl(e-Ou-n)==="docked"}function Mu(e){return Number.isNaN(e)?ws:Math.min(No,Math.max(Do,e))}function y0(e,t=$o){return Math.max(0,Math.min(No,e-Lo-t))}function lI(e,t,n=ws,r=!1,s=$o){const i=!t&&r&&g0(e,n,s),a=t||i,c=y0(e,s);return{mode:a?"strip":"docked",width:a?Ou:Math.min(Mu(n),c),collapsed:a,resizable:!a&&c>=Do}}function dI(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="b"}const uI=e=>e?"⌘B":"Ctrl+B",_0=()=>{const e=v.useContext(Ao)??null,t=v.useMemo(()=>new rw({defaultOptions:{queries:{enabled:!1,retry:!1}}}),[]);return v.useMemo(()=>e?{client:e,provided:!0}:{client:t,provided:!1},[e,t])},Du={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},v0=3e4,b0=15e3;function w0(e){return e?.desktop_available===!0}function fI(){const{client:e,provided:t}=_0();return _u({enabled:t,queryKey:Du.capabilities,queryFn:async()=>{try{return await xe({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>w0(n.state.data)?v0:b0,refetchIntervalInBackground:!0},e)}function S0(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function pI(e,t,n=1){return S0(e,t,n)==="enabled"}function hI(e){return _u({queryKey:Du.providers,queryFn:()=>xe({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:p0})}const k0="data-canvas-shortcuts",R0=`[${k0}]`,E0=e=>Nu(e,R0),I0='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',mI=e=>Nu(e,I0);function Nu(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const gI=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&E0(e.target)?"new-file":null},x0=["active","created"],yI={running:"Running",today:"Today",week:"This week",older:"Older"},T0=new Set(["waiting","busy","delegating","approval","answer","wedged"]);function Ss(e){return T0.has(e.status?.code??"")}const C0=new Set(["approval","answer"]);function A0(e){return C0.has(e.status?.code??"")}const O0=24*60*60*1e3,P0=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()};function Uo(e,t){const n=t==="created"?e.created_at:e.updated_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}const j0="last_user_at";function M0(e){const t=e[j0],n=typeof t=="number"&&Number.isFinite(t)&&t>0?t:e.created_at;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:n*1e3}function D0(e,t,n){if(Ss(e))return"running";const r=Uo(e,n);if(r===null)return"older";const s=P0(t);return r>=s?"today":r>=s-6*O0?"week":"older"}function _I(e,t,n){const r={running:[],today:[],week:[],older:[]};for(const s of e)r[D0(s,t,n)].push(s);return r}function N0(e,t,n){const r=Uo(e,n);if(r===null)return"";const s=Math.floor(Math.max(0,t-r)/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const i=Math.floor(s/60);if(i<24)return`${i}h`;const a=Math.floor(i/24);if(a<7)return`${a}d`;const c=Math.floor(a/7);return a<365?`${c}w`:`${Math.floor(a/365)}y`}function vI(e,t,n){const r=N0(e,t,n);if(!r)return"";const s=n==="created"?"created":"last active";if(r==="now")return`${s} just now`;const i={m:"minute",h:"hour",d:"day",w:"week",y:"year"},a=Number.parseInt(r,10),c=i[r.slice(-1)];return`${s} ${a} ${c}${a===1?"":"s"} ago`}const Qi=["pinned","running","today","week","older","agents","teams"];function bI(e){return e==="agents"||e==="teams"}const yr=8;function L0(e,t){if(!(t in e))return e;const n={...e};return delete n[t],n}function wI(e,t){return{...e,[t]:(e[t]??yr)+yr}}function SI(e,t,n,r,s){const i=!(e[n]??r);return{expanded:{...e,[n]:i},caps:!i&&!s?L0(t,n):t}}function kI(e,t,n,r){return(e||t!=="")&&(r>yr||n.trim()!=="")}const RI="Collapse, then reopen, to restore the compact list";function EI(e){return(e??yr)>yr}const II=e=>`section-grown-hint-${e}`,$0=e=>e===1?"Show 1 more":`Show ${e} more`;function xI(e,t){return`${$0(e)} ${t}`}const pn={hidden:[],order:[...Qi],pins:[],groupBy:"section",tagsEnabled:!1,autoTagForks:!0,basis:"active",orderBy:"active-first",loads:0,pinnedAgents:[]},U0=10,$n=[25,50],F0=50,B0=500,G0=64;function bn(e){const t=Math.max(0,Math.floor(e));return t===0?U0:t<=$n.length?$n[t-1]:$n[$n.length-1]+(t-$n.length)*F0}function TI(e,t){const n=bn(e+1)-bn(e),r=Math.max(0,Math.min(n,t));return r===1?"Show 1 more chat":`Show ${r} more chats`}function CI(e,t,n){const r=bn(t+1)-bn(t),s=bn(t),i=Math.min(s+r,e.length);let a=0;for(let l=s;l<i;l+=1)Fo(e[l])&&(a+=1);const c=Math.max(0,i-s-a);return c>0?c:Math.max(0,Math.min(r,n))}function Fo(e){return Ss(e)}function H0(e){return A0(e)?0:Ss(e)?1:2}function W0(e,t){return Ss(e)?M0(e):Uo(e,t)}function z0(e,t){return e===null&&t===null?0:e===null?1:t===null?-1:t-e}function AI(e,t,n){const r=e.map((s,i)=>({row:s,index:i,lane:t==="active-first"?H0(s):0,at:W0(s,n)}));return r.sort((s,i)=>s.lane-i.lane||z0(s.at,i.at)||s.index-i.index),r.map(s=>s.row)}function OI(e,t){const{limit:n,currentId:r,searching:s=!1}=t;if(s)return{rows:[...e],lifted:!1,remaining:0};const i=[];let a=Math.max(0,n);for(const d of e){if(a>0){i.push(d),a-=1;continue}Fo(d)&&i.push(d)}const c=Math.max(0,e.length-i.length);if(!r)return{rows:i,lifted:!1,remaining:c};const l=e.find(d=>d.session_id===r)??null;return l===null||i.includes(l)?{rows:i,lifted:!1,remaining:c}:{rows:[l,...i],lifted:!0,remaining:c}}function PI(e,t){if(t.searching)return{rows:[...e],lifted:!1,hidden:0,held:e.length};const n=bn(t.loads),r=[];let s=n;for(const l of e){if(Fo(l)){r.push(l);continue}s>0&&(r.push(l),s-=1)}const i=t.currentId,a=i==null?null:e.find(l=>l.session_id===i)??null,c=a!==null&&!r.includes(a);return{rows:c&&a!==null?[a,...r]:r,lifted:c,hidden:e.length-r.length-(c?1:0),held:e.length}}function jI(e){if(e.add<=0)return null;const t=e.add===1?"Show 1 more chat":`Show ${e.add} more chats`;if(e.drawn>=e.total)return{label:t,aria:t};const n=`${e.drawn} of ${e.total}`;return{label:`${t} · ${n}`,aria:`${t} · ${n} shown`}}const Z0="mt-4",V0="mt-2";function MI(e){return e?Z0:V0}function DI(e,t,n,r){return n?e.toLocaleLowerCase().includes(n.toLocaleLowerCase())||(r??"").toLocaleLowerCase().includes(n.toLocaleLowerCase())||t>0:!0}function NI(e,t){if(t==="section")return null;if(t==="flat")return[{key:"all",label:"",rows:[...e]}];const n=new Map;for(const i of e){const a=i.binding?.team||i.binding?.agent||"",c=a||"ungrouped",l=n.get(c)??{key:c,label:a||"Ungrouped",rows:[]};l.rows.push(i),n.set(c,l)}const r=[...n.values()],s=r.findIndex(i=>i.key==="ungrouped");return s>0&&r.push(...r.splice(s,1)),r}function K0(e,t){return!e.hidden.includes(t)}function Lu(e){return e.order.filter(t=>K0(e,t))}function LI(e,t){const n=e.hidden.includes(t)?e.hidden.filter(r=>r!==t):[...e.hidden,t];return{...e,hidden:n}}function $I(e,t,n){const r=Lu(e),s=r.indexOf(t),i=r[s+n];if(s<0||i===void 0)return e;const a=e.order.indexOf(t),c=e.order.indexOf(i),l=[...e.order];return l[a]=i,l[c]=t,{...e,order:l}}const Y0=["running","today","week","older"];function nl(e){return Y0.includes(e)}function UI(e,t,n,r){if(!nl(t)||r&&!r(t))return!1;const s=Lu(e),i=s.indexOf(t);if(i<0)return!1;const a=s[i+n];return a===void 0||!nl(a)?!1:r?r(a):!0}const Q0=["section","agent","flat"],J0=["active-first","recent"];function FI(e){if(typeof e!="object"||e===null)return pn;const t=e,n=new Set(Qi),r=[];if(Array.isArray(t.order))for(const p of t.order)typeof p=="string"&&n.has(p)&&(r.includes(p)||r.push(p));for(const p of Qi)r.includes(p)||r.push(p);const s=[];if(Array.isArray(t.hidden))for(const p of t.hidden)typeof p=="string"&&n.has(p)&&(s.includes(p)||s.push(p));const i=Q0.includes(t.groupBy)?t.groupBy:pn.groupBy,a=x0.includes(t.basis)?t.basis:pn.basis,c=J0.includes(t.orderBy)?t.orderBy:pn.orderBy,l=typeof t.loads=="number"&&Number.isFinite(t.loads)&&t.loads>0?Math.min(B0,Math.floor(t.loads)):0,d=[];if(Array.isArray(t.pinnedAgents)){for(const p of t.pinnedAgents)if(typeof p=="string"&&p!==""&&!d.includes(p)){if(d.length>=G0)break;d.push(p)}}const u=[],f=new Set;if(Array.isArray(t.pins))for(const p of t.pins)typeof p=="string"&&p.length!==0&&(f.has(p)||(f.add(p),u.push(p)));return{hidden:s,order:r,groupBy:i,tagsEnabled:typeof t.tagsEnabled=="boolean"?t.tagsEnabled:!1,autoTagForks:typeof t.autoTagForks=="boolean"?t.autoTagForks:pn.autoTagForks,basis:a,orderBy:c,loads:l,pins:u,pinnedAgents:d}}const $u={sort:"recent",order:"asc",group:!0,workingOpen:!1,closedSections:[],kinds:[]},X0=["recent","name","kind","modified","created","size"],q0=["images","video","audio","documents","spreadsheets","presentations","code","archives","other"];function Bo(e){const t=e&&typeof e=="object"?e:{};return{sort:X0.includes(t.sort??"")?t.sort:$u.sort,order:t.order==="desc"?"desc":"asc",group:typeof t.group=="boolean"?t.group:!0,workingOpen:t.workingOpen===!0,closedSections:Array.isArray(t.closedSections)?[...new Set(t.closedSections.filter(n=>["Highlights","Images","Videos","Sounds","Documents","Spreadsheets","Other"].includes(n)))]:[],kinds:Array.isArray(t.kinds)?[...new Set(t.kinds.filter(n=>q0.includes(n)))]:[]}}function BI(e,t){const n=r=>{switch(t.sort){case"name":return r.row.name;case"kind":return`${r.row.kind}\0${r.row.name}`;case"modified":return r.modified;case"created":return r.created;case"size":return r.row.document.sizeBytes??null;default:return r.mentioned}};return[...e].sort((r,s)=>{const i=n(r),a=n(s);if(i===null||a===null)return i===a?0:i===null?1:-1;const c=typeof i=="string"&&typeof a=="string"?i.localeCompare(a,void 0,{numeric:!0}):Number(i)-Number(a);return(t.order==="asc"?c:-c)||r.mentioned-s.mentioned})}const eS=e=>{switch(e.row.kind){case"images":return"Images";case"video":return"Videos";case"audio":return"Sounds";case"spreadsheets":return"Spreadsheets";case"documents":case"presentations":case"code":return"Documents";default:return"Other"}};function GI(e,t,n,r){const s=e.filter(c=>c.highlighted),i=e.filter(c=>!c.highlighted),a=[];if(s.length&&a.push({id:"Highlights",label:"Highlights",items:s,open:n||!r.has("Highlights"),highlights:!0}),s.length&&i.length&&(a.push({id:"Working files",label:"Working files",items:[],open:t.workingOpen||n,highlights:!1}),!t.workingOpen&&!n))return a;if(!t.group)i.length&&a.push({id:"Files",label:"Files",items:i,open:!0,highlights:!1});else for(const c of["Images","Videos","Sounds","Documents","Spreadsheets","Other"]){const l=i.filter(d=>eS(d)===c);l.length&&a.push({id:c,label:c,items:l,open:n||!r.has(c),highlights:!1})}return a}const tS=32,HI=4;function WI(e,t,n){const r=[],s=new Map,i=Math.max(136,t-16),a=Math.max(1,Math.floor((i+4)/140));let c=0;const l=(d,u,f,p,h=1)=>{p.forEach((g,m)=>s.set(g.row.document.id,{band:r.length,column:m})),r.push({section:d,kind:u,height:f,top:c,items:p,cols:h}),c+=f};for(const d of e)if(l(d,"header",tS,[]),!!d.open)if(d.highlights)for(const u of d.items)l(d,"highlight",u.why?68:44,[u]);else if(n&&d.id==="Images"){const u=(i-4*(a-1))/a,f=Math.round((u-8)*3/4)+32;for(let p=0;p<d.items.length;p+=a)l(d,"tiles",f,d.items.slice(p,p+a),a)}else if(n&&d.id==="Videos")for(const u of d.items)l(d,"video",Math.min(Math.round((i-8)*9/16),280)+32,[u]);else if(n&&d.id==="Sounds")for(const u of d.items)l(d,"audio",80,[u]);else for(const u of d.items)l(d,"compact",36,[u]);return{bands:r,height:c,columns:a,positions:s}}function zI(e,t,n,r){const s=Math.max(600,n*.75);let i=0,a=e.bands.length;for(;i<a;){const d=i+a>>>1,u=e.bands[d];u.top+u.height<t-s?i=d+1:a=d}const c=new Set;for(let d=i;d<e.bands.length&&e.bands[d].top<=t+n+s;d++)c.add(d);const l=r?e.positions.get(r):null;return l&&c.add(l.band),[...c].sort((d,u)=>d-u)}function ZI(e,t,n,r){const s=e.positions.get(t);if(!s)return null;const i=e.bands[s.band],a=e.bands.filter(u=>u.section.id===i.section.id&&u.items.length);if(n==="Home")return a[0]?.items[0]?.row.document.id??null;if(n==="End")return a.at(-1)?.items.at(-1)?.row.document.id??null;if(n==="ArrowLeft"||n==="ArrowRight")return i.items[s.column+(n==="ArrowLeft"?-1:1)]?.row.document.id??null;const c=n==="ArrowUp"||n==="PageUp"?-1:1,l=i.top+(n.startsWith("Page")?r*c:c);let d=s.band+c;for(;d>=0&&d<e.bands.length;d+=c){const u=e.bands[d];if(u.items.length&&!(n.startsWith("Page")&&(c>0?u.top<l:u.top>l)))return u.items[Math.min(s.column,u.items.length-1)].row.document.id}if(n.startsWith("Page")){const u=e.bands.filter(p=>p.items.length),f=c<0?u[0]:u.at(-1);return f?.items[c<0?0:f.items.length-1]?.row.document.id??null}return null}const nS="both",Uu="by-turn",Ji=[{value:"by-turn",label:"By turn"},{value:"by-response",label:"By response"}];function VI(e){for(const t of Ji)if(e===t.value)return t.value;return Uu}function KI(e){return Ji.find(t=>t.value===e)?.label??Ji[0].label}const YI="primary+alt+shift+space",rS=/^f([1-9]|1[0-9]|2[0-4])$/;function sS(e){return rS.test(e)}function iS(e,t){const n=oS(e,t);return t==="mac"?n.join(""):n.join("+")}function oS(e,t){const r=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},s={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 r?r[i]:i in s?s[i]:sS(i)||i.length===1?i.toUpperCase():i)}const ks=[{id:"panel.console",label:"Open console",category:"Panels",defaultChord:"primary+j",scope:"app"},{id:"panel.canvas",label:"Open canvas",category:"Panels",defaultChord:"primary+shift+c",scope:"app"},{id:"panel.run",label:"Open run details",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.ask",label:"Open asks",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.browser",label:"Open browser",category:"Panels",defaultChord:null,scope:"app"},{id:"panel.code",label:"Open code review",category:"Panels",defaultChord:null,scope:"app"}],aS=new Map(ks.map(e=>[e.id,e])),cS=e=>aS.get(e),lS=new Set(["primary+0","primary+r","primary+shift+r","primary+t","primary+shift+t","primary+l",...[1,2,3,4,5,6,7,8,9].map(e=>`primary+${e}`)]),Go=new Map([["primary+p","Reserved: opens the command palette from anywhere."],["primary+shift+p","Reserved: opens the command palette on commands."],["primary+shift+s","Reserved: starts speech to text."],["primary+k","Reserved: opens the command palette on chats."],["primary+n","Reserved: starts a new chat."],["primary+b","Reserved: toggles the sidebar."],["primary+[","Reserved: goes back in the browser, or between chats outside it."],["primary+]","Reserved: goes forward in the browser, or between chats outside it."],["primary+f","Reserved: finds in the browser page, or searches the transcript outside it."],["primary+alt+up","Reserved: walks up the chat regions."],["primary+alt+down","Reserved: walks down the chat regions."],["primary+shift+a","Reserved: archives the focused conversation."],["primary+shift+l","Reserved: opens the focused conversation's tags."],["primary+s","Reserved: saves the canvas document."],["primary+o","Reserved: opens a file in the canvas."],["primary+shift+up","Reserved: moves the focused chat up the pinned order."],["primary+shift+down","Reserved: moves the focused chat down the pinned order."],["primary+c","Reserved: copy."],["primary+x","Reserved: cut."],["primary+v","Reserved: paste."],["primary+a","Reserved: select all."],["primary+z","Reserved: undo."],["primary+shift+z","Reserved: redo."],["primary+y","Reserved: redo on Windows and Linux."],["primary+r","Reserved: reloads the browser page."],["primary+shift+r","Reserved: reloads the browser page, ignoring the cache."],["primary+t","Reserved: opens a new browser tab."],["primary+shift+t","Reserved: reopens the last closed browser tab."],["primary+l","Reserved: focuses the browser address bar."],...[1,2,3,4,5,6,7,8,9].map(e=>[`primary+${e}`,e===9?"Reserved: switches to the last browser tab.":`Reserved: switches to browser tab ${e}.`]),["primary+0","Reserved: resets browser page zoom, or app zoom outside it."],["primary+plus","Reserved: zooms the browser page or app in."],["primary+=","Reserved: zooms the browser page or app in."],["primary+-","Reserved: zooms the browser page or app out."],["primary+q","Reserved: quits the app."],["primary+w","Reserved: closes the browser tab, or the window outside it."],["primary+m","Reserved: minimises the window."]]),dS=["primary","alt","shift"],uS={primary:"primary",meta:"primary",cmd:"primary",command:"primary",super:"primary",ctrl:"primary",control:"primary",alt:"alt",option:"alt",shift:"shift"},fS=new Set(["space","backspace","delete","insert","home","end","pageup","pagedown","up","down","left","right"]),pS=e=>fS.has(e)||/^[a-z0-9]$/.test(e);function Ho(e){if(typeof e!="string")return null;const t=e.toLowerCase().split("+").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;const n=t[t.length-1];if(!pS(n))return null;const r=new Set;for(const i of t.slice(0,-1)){const a=uS[i];if(a===void 0)return null;r.add(a)}return[...dS.filter(i=>r.has(i)),n].join("+")}const Fu=e=>e.split("+").includes("primary");function Rs(e,t){const n=t?.[e];return n===null?null:typeof n=="string"&&!Go.has(n)?n:cS(e)?.defaultChord??null}function QI(e){const t=new Map;for(const n of ks){const r=Rs(n.id,e);r!==null&&!t.has(r)&&t.set(r,n.id)}return t}const hS=e=>e==="mac"?"A shortcut needs ⌘ or Ctrl.":"A shortcut needs Ctrl.";function mS(e,t,n,r="linux"){const s=e===null?null:Ho(e);if(s===null)return"That key cannot be bound.";if(!Fu(s))return hS(r);const i=Go.get(s);if(i!==void 0)return i;for(const a of ks)if(a.id!==t&&Rs(a.id,n)===s)return`Already assigned to ${a.label}.`;return null}function gS(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const t=e,n=new Set,r={};for(const s of ks){const i=t[s.id];if(i===null){r[s.id]=null;continue}const a=typeof i=="string"?Ho(i):null,c=a!==null&&lS.has(a),l=a!==null&&Fu(a)&&(c||!Go.has(a)&&!n.has(a))?a:null;l!==null&&(r[s.id]=l);const d=Rs(s.id,r);d!==null&&n.add(d)}return r}function JI(e,t,n){const r=Rs(e,t);return r===null?null:Bu(r,n)}function Bu(e,t){return iS(e,t)}function XI(e,t){const n=e.split("+"),r=n[n.length-1],s=n.slice(0,-1).map(i=>i==="primary"?t==="mac"?"Meta":"Control":i==="shift"?"Shift":i==="alt"?"Alt":i);return{glyph:Bu(e,t),aria:[...s,r.length===1?r.toUpperCase():r].join("+")}}const rl=64,Xi=["canvas","run","browser","console","code"],yS={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"};function Gu(e){return typeof e=="string"&&Xi.includes(e)}function Wo(e){return e.startsWith("draft:")}function kr(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r[0]===t)return r[1]}}function zo(e){return e.length>rl?e.slice(e.length-rl):e}function Hu(e,t,n){return zo([...e.filter(([r])=>r!==t),[t,n]])}function _S(e,t,n){return kr(e,t)!==n?e:e.filter(([r])=>r!==t)}function vS(e,t){return kr(e,t)===void 0?e:e.filter(([n])=>n!==t)}function bS(e,t,n){const r=kr(e,t);return r===void 0?e:zo([...e.filter(([s])=>s!==t&&s!==n),[n,r]])}const sl=Object.freeze({isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1});function il(e,t,n){if(n||typeof t!="string")return sl;const r=kr(e,t);return r===void 0?sl:{isCanvasOpen:r==="canvas",isRunPanelOpen:r==="run",isBrowserPaneOpen:r==="browser",isConsolePaneOpen:r==="console",isCodeReviewPaneOpen:r==="code"}}function wS(e){if(!Array.isArray(e))return[];const t=new Map;for(const n of e){if(!Array.isArray(n)||n.length!==2)continue;const[r,s]=n;typeof r!="string"||r===""||Wo(r)||Gu(s)&&(t.delete(r),t.set(r,s))}return zo([...t.entries()])}function qI(e){const t=new Set(Object.keys(e.forgotten));for(const[n,r]of Object.entries(e.archiveFacts))r?.archived===!0&&r.answered===!0&&t.add(n);return t}function ol(e){return yS[e]}const SS={canvas:"isCanvasOpen",run:"isRunPanelOpen",browser:"isBrowserPaneOpen",console:"isConsolePaneOpen",code:"isCodeReviewPaneOpen"},Rr=e=>e.isCanvasOpen?"canvas":e.isRunPanelOpen?"run":e.isBrowserPaneOpen?"browser":e.isConsolePaneOpen?"console":e.isCodeReviewPaneOpen?"code":e.isAskDrawerOpen?"ask":null,Es=(e,t)=>e==="ask"?t.askDrawerScope==="fleet"||t.rightSlotRoute.mounted&&t.rightSlotRoute.session:t.rightSlotRoute.mounted,kS=e=>{const t=Rr(e);return t===null||t==="ask"?null:SS[t]},Ct=e=>({isRunPanelOpen:e==="isRunPanelOpen",isCanvasOpen:e==="isCanvasOpen",isBrowserPaneOpen:e==="isBrowserPaneOpen",isConsolePaneOpen:e==="isConsolePaneOpen",isCodeReviewPaneOpen:e==="isCodeReviewPaneOpen",isAskDrawerOpen:e==="isAskDrawerOpen",askDrawerEvictedPane:null}),Gt=(e,t)=>{const n=e.rightSlotKey;return typeof n!="string"?{}:{rightSlotMemory:Hu(e.rightSlotMemory,n,t)}},Un=(e,t)=>{const n=e.rightSlotKey;if(typeof n!="string")return{};const r=_S(e.rightSlotMemory,n,t);return r===e.rightSlotMemory?{}:{rightSlotMemory:r}},RS=e=>{const t=e.rightSlotKey;if(typeof t!="string")return{};const n=vS(e.rightSlotMemory,t);return n===e.rightSlotMemory?{}:{rightSlotMemory:n}},ES=Object.freeze({mounted:!1,session:!1}),Wu=Object.freeze([]);function ex(e,t){const n=Rr(t);if(n===null||!Es(n,t))return 0;let r;switch(n){case"canvas":case"ask":r=Math.max(Pu,t.rightSlotWidth||Fn);break;case"run":r=Math.max(cl,t.rightSlotWidth||Fn);break;case"browser":r=Math.max(CS,t.rightSlotWidth||Fn);break;case"console":r=Math.max(AS,t.rightSlotWidth||Fn);break;case"code":r=Math.max(cl,t.rightSlotWidth||Fn);break}return e<=0?r:n==="canvas"||n==="ask"?Math.min(r,ju(e)):Math.min(r,Math.max(0,e-Lo))}function tx(e){const t=Rr(e);return t!==null&&Es(t,e)}function nx(e){const t=Rr(e);return t!==null&&Es(t,e)?t:null}function rx(e){const t=Rr(e);return(t==="canvas"||t==="ask")&&Es(t,e)}const Fn=640,al=ws,IS=20,xS=4,TS=20,cl=320,CS=480,AS=480,OS=5e3,sx=(e,t)=>e.some(n=>n.surface===t),ix=(e,t=Date.now())=>e.some(n=>t-n.at<OS),PS=[],jS=4,MS=["chatMeasureWidth"],ox=vr()(hs((e,t)=>({finderFiles:$u,setFinderFiles:n=>e({finderFiles:Bo({...t().finderFiles,...n})}),isCommandPaletteOpen:!1,commandPaletteQuery:"",isSidebarCollapsed:!1,sidebarOverflowExpanded:!1,showAgentReasoning:!1,transcriptDisplayMode:Uu,themeName:qu,rightSlotWidth:0,chatSidebarWidth:al,chatSidebarRegions:nS,chatSidebarView:pn,chatSidebarListHeight:null,chatSidebarOrder:"entities-first",dismissedBuiltinOfferSignature:"",isCanvasOpen:!1,isRunPanelOpen:!1,isBrowserPaneOpen:!1,isConsolePaneOpen:!1,isCodeReviewPaneOpen:!1,rightSlotKey:void 0,rightSlotMemory:Wu,rightSlotLegacySeed:null,isAskDrawerOpen:!1,askDrawerScope:"session",askDrawerEvictedPane:null,askOpenIntent:null,rightSlotRoute:ES,consoleOpenIntent:null,consoleLiveSurface:null,runPanelReveal:null,codeReviewReveal:null,browserPaneScope:"conversation",consoleActiveSurface:null,consoleUnseen:PS,isCreateAgentDialogOpen:!1,mentionRecents:null,profileRecents:{agent:[],team:[]},conversationRecents:[],shortcutBindings:{},openCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!0})},closeCreateAgentDialog:()=>{e({isCreateAgentDialogOpen:!1})},openCommandPalette:()=>{e({isCommandPaletteOpen:!0})},closeCommandPalette:()=>{e({isCommandPaletteOpen:!1,commandPaletteQuery:""})},toggleCommandPalette:(n="")=>{e(r=>({isCommandPaletteOpen:!r.isCommandPaletteOpen,commandPaletteQuery:r.isCommandPaletteOpen?r.commandPaletteQuery:n}))},setCommandPaletteQuery:n=>{e({commandPaletteQuery:n})},toggleSidebar:()=>{e(n=>({isSidebarCollapsed:!n.isSidebarCollapsed}))},setSidebarOverflowExpanded:n=>{e({sidebarOverflowExpanded:n})},setSidebarCollapsed:n=>{e({isSidebarCollapsed:n})},setShowAgentReasoning:n=>{e({showAgentReasoning:n})},setTranscriptDisplayMode:n=>{e({transcriptDisplayMode:n})},setTheme:n=>{e({themeName:n})},setCanvasOpen:n=>{e(r=>n?{...Ct("isCanvasOpen"),...Gt(r,"canvas")}:{isCanvasOpen:!1,...Un(r,"canvas")})},setRunPanelOpen:n=>{e(r=>n?{...Ct("isRunPanelOpen"),...Gt(r,"run")}:{isRunPanelOpen:!1,...Un(r,"run")})},setBrowserPaneOpen:n=>{e(r=>n?{...Ct("isBrowserPaneOpen"),...Gt(r,"browser")}:{isBrowserPaneOpen:!1,...Un(r,"browser")})},setConsolePaneOpen:n=>{e(r=>n?{...Ct("isConsolePaneOpen"),...Gt(r,"console")}:{isConsolePaneOpen:!1,...Un(r,"console")})},setCodeReviewPaneOpen:n=>{e(r=>n?{...Ct("isCodeReviewPaneOpen"),...Gt(r,"code")}:{isCodeReviewPaneOpen:!1,...Un(r,"code")})},clearCodeReviewReveal:n=>{e(r=>r.codeReviewReveal?.nonce===n?{codeReviewReveal:null}:{})},revealCodeReviewPane:()=>{e(n=>({...Ct("isCodeReviewPaneOpen"),...Gt(n,"code"),codeReviewReveal:{nonce:(n.codeReviewReveal?.nonce??0)+1}}))},setAskDrawerOpen:(n,r,s)=>{e(i=>{const a=typeof i.rightSlotKey=="string";if(n)return{...Ct("isAskDrawerOpen"),askDrawerScope:r,askDrawerEvictedPane:a?null:kS(i),askOpenIntent:null};const c={isAskDrawerOpen:!1,askDrawerEvictedPane:null,askOpenIntent:null};return a?s?.dismissSlot?{...c,...RS(i)}:{...c,...il(i.rightSlotMemory,i.rightSlotKey,!1)}:i.rightSlotKey===null?s?.dismissSlot?{...c,rightSlotLegacySeed:null}:c:s?.dismissSlot?{...c,rightSlotLegacySeed:null}:{...c,...i.askDrawerEvictedPane===null?null:{[i.askDrawerEvictedPane]:!0}}})},requestAskOpen:(n,r="menu")=>{e({askOpenIntent:{scope:n,via:r}})},clearAskOpenIntent:n=>{e(r=>r.askOpenIntent?.scope===n?{askOpenIntent:null}:{})},setConsoleActiveSurface:n=>{e({consoleActiveSurface:n})},requestConsoleOpen:n=>{e({consoleOpenIntent:n})},clearConsoleOpenIntent:n=>{e(r=>r.consoleOpenIntent===n?{consoleOpenIntent:null}:{})},setConsoleLiveSurface:(n,r)=>{e(s=>{if(n===null||r<=0)return s.consoleLiveSurface===null?{}:{consoleLiveSurface:null};const i=s.consoleLiveSurface;return i?.sessionId===n&&i.count===r?{}:{consoleLiveSurface:{sessionId:n,count:r}}})},markConsoleUnseen:(n,r)=>{e(s=>s.consoleUnseen.some(i=>i.surface===r)?{}:{consoleUnseen:[...s.consoleUnseen,{sessionId:n,surface:r,at:Date.now()}]})},clearConsoleUnseen:n=>{const r=Array.isArray(n)?n:[n];e(s=>{const i=s.consoleUnseen.filter(a=>!r.includes(a.surface));return i.length===s.consoleUnseen.length?{}:{consoleUnseen:i}})},setRightSlotWidth:n=>{e({rightSlotWidth:n})},restoreDefaultRightSlotWidth:()=>{e({rightSlotWidth:0})},bindRightSlotKey:(n,r)=>{e(s=>{let i=s.rightSlotMemory,a=s.rightSlotLegacySeed;const c=r?.admittedFrom;return typeof c=="string"&&typeof n=="string"&&(i=bS(i,c,n)),n===null||(Wo(n)?a=null:a!==null&&kr(i,n)===void 0&&(i=Hu(i,n,a),a=null)),{rightSlotKey:n,rightSlotMemory:i,rightSlotLegacySeed:a,...il(i,n,s.isAskDrawerOpen)}})},setRightSlotRoute:n=>{const r=t().rightSlotRoute;r.mounted===n.mounted&&r.session===n.session||e({rightSlotRoute:{...n}})},setShortcutBinding:(n,r)=>{if(r===null){e(i=>{const a={...i.shortcutBindings};return delete a[n],{shortcutBindings:a}});return}const s=Ho(r);s!==null&&mS(s,n,t().shortcutBindings)===null&&e(i=>({shortcutBindings:{...i.shortcutBindings,[n]:s}}))},clearShortcutBinding:n=>{e(r=>({shortcutBindings:{...r.shortcutBindings,[n]:null}}))},setBrowserPaneScope:n=>{e({browserPaneScope:n})},revealRunPanelSection:n=>{e(r=>({...Ct("isRunPanelOpen"),...Gt(r,"run"),runPanelReveal:{section:n,nonce:(r.runPanelReveal?.nonce??0)+1}}))},clearRunPanelReveal:n=>{e(r=>r.runPanelReveal?.nonce===n?{runPanelReveal:null}:{})},setChatSidebarWidth:n=>{e({chatSidebarWidth:Math.min(No,Math.max(Do,n))})},setChatSidebarRegions:n=>{e({chatSidebarRegions:n})},setChatSidebarListHeight:n=>{e({chatSidebarListHeight:n})},restoreDefaultChatSidebarListHeight:()=>{e({chatSidebarListHeight:null})},setChatSidebarOrder:n=>{e({chatSidebarOrder:n})},setChatSidebarView:n=>{e({chatSidebarView:n})},dismissBuiltinOffer:n=>{e({dismissedBuiltinOfferSignature:n})},restoreDefaultChatSidebarWidth:()=>{e({chatSidebarWidth:al})},rememberMention:(n,r)=>{e(s=>{const i=s.mentionRecents,a=i?.cwd===n?i.paths:[],c=[r,...a.filter(l=>l!==r)].slice(0,IS);return{mentionRecents:{cwd:n,paths:c}}})},rememberProfile:(n,r)=>{e(s=>({profileRecents:{...s.profileRecents,[n]:DS(s.profileRecents[n]??[],r)}}))},rememberConversation:n=>{e(r=>{const s=$S(r.conversationRecents),i=NS(s,n);return i.length===s.length&&i.every((a,c)=>a===s[c])?r:{conversationRecents:i}})}}),{name:"ui-preferences-storage",version:jS,migrate:GS,partialize:US,merge:BS}));function DS(e,t){return[t,...e.filter(n=>n!==t)].slice(0,xS)}function NS(e,t){return[t,...e.filter(n=>n!==t)].slice(0,TS)}const LS=[];function $S(e){return Array.isArray(e)?e:LS}function US(e){const{runPanelReveal:t,codeReviewReveal:n,consoleOpenIntent:r,consoleLiveSurface:s,askOpenIntent:i,isAskDrawerOpen:a,askDrawerScope:c,askDrawerEvictedPane:l,rightSlotRoute:d,isCanvasOpen:u,isRunPanelOpen:f,isBrowserPaneOpen:p,isConsolePaneOpen:h,isCodeReviewPaneOpen:g,rightSlotKey:m,...y}=e;return{...y,rightSlotMemory:FS(e.rightSlotMemory)}}function FS(e){return(e??Wu).filter(([t])=>!Wo(t))}function BS(e,t){const n=e??{},{isCanvasOpen:r,isRunPanelOpen:s,isBrowserPaneOpen:i,isConsolePaneOpen:a,isCodeReviewPaneOpen:c,...l}=n;return{...t,...l,finderFiles:Bo(n.finderFiles),rightSlotKey:t.rightSlotKey,rightSlotMemory:wS(n.rightSlotMemory),rightSlotLegacySeed:Gu(n.rightSlotLegacySeed)?n.rightSlotLegacySeed:null,shortcutBindings:gS(n.shortcutBindings)}}function GS(e,t){const n={...e??{}};if(t<1&&HS(n),t<2)for(const r of MS)delete n[r];if(t<3){let r=null;for(const s of Xi)if(n[ol(s)]===!0){r=s;break}r!==null&&(n.rightSlotLegacySeed=r);for(const s of Xi)delete n[ol(s)]}return t<4&&(n.finderFiles=Bo(n.finderFiles)),n}function HS(e){const t=[["canvasWidth",800],["runPanelWidth",420],["browserPanelWidth",640],["consolePanelWidth",796]];let n=0;for(const[r,s]of t){const i=e[r];if(typeof i=="number"&&i>0&&i!==s){n=i;break}}for(const[r]of t)delete e[r];e.rightSlotWidth=n}const qi=e=>e.replace(/\\/g,"/"),ax=()=>window.location.hash?qi(window.location.hash.substring(1)):qi(window.location.pathname),cx=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},lx=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const s=n[0]==="~"||n[0]==="",i=s?n.slice(0,2):n.slice(0,1),a=n.slice(i.length),c=g=>{const m=t-g.length-(g?3:2);let y=[];for(let _=a.length-1;_>=0;_-=1){const b=[a[_],...y];if(b.join("/").length>m)break;y=b}return y},l=(g,m)=>g?`${g}/…/${m.join("/")}`:`…/${m.join("/")}`,d=i.join("/"),u=c(d);if(u.length>0)return u.length===a.length?e:l(d,u);const f=s?n[0]:"",p=c(f);if(p.length>0)return l(f,p);const h=t-(f?`${f}/…/`.length:2);return h>0?l(f,[r.slice(-h)]):"…"},dx=(e,t)=>qi(e).includes(t);export{hs as $,Zw as A,VE as B,_E as C,ye as D,Zd as E,pE as F,Vd as G,hE as H,yE as I,fE as J,gE as K,S0 as L,ax as M,YE as N,tu as O,Pa as P,OE as Q,mE as R,Fe as S,PE as T,Yd as U,bs as V,mI as W,$S as X,vr as Y,rE as Z,l0 as _,fI as a,kl as a$,Du as a0,zp as a1,sw as a2,zc as a3,HE as a4,GE as a5,vw as a6,iI as a7,vk as a8,th as a9,uw as aA,gw as aB,pw as aC,hw as aD,Kc as aE,_w as aF,Yc as aG,yw as aH,mw as aI,dx as aJ,KS as aK,VS as aL,ZS as aM,YS as aN,_p as aO,st as aP,Yn as aQ,tm as aR,nx as aS,JI as aT,Je as aU,eE as aV,$t as aW,ma as aX,no as aY,ah as aZ,fs as a_,nh as aa,$a as ab,ek as ac,qS as ad,QS as ae,DR as af,CR as ag,OR as ah,PR as ai,$d as aj,ks as ak,Rs as al,Bu as am,mS as an,og as ao,bb as ap,oI as aq,Ji as ar,VI as as,FE as at,Cb as au,Tb as av,Sr as aw,Pe as ax,lu as ay,cw as az,tI as b,xI as b$,Jv as b0,uE as b1,X as b2,fn as b3,dE as b4,Mi as b5,Di as b6,cE as b7,lE as b8,sE as b9,bI as bA,LI as bB,$I as bC,UI as bD,wE as bE,vE as bF,nu as bG,UE as bH,FI as bI,AI as bJ,OI as bK,bn as bL,pn as bM,_I as bN,Lu as bO,kI as bP,DI as bQ,yr as bR,MI as bS,NI as bT,TI as bU,CI as bV,$c as bW,EI as bX,RI as bY,II as bZ,$0 as b_,iE as ba,oE as bb,XI as bc,ix as bd,OS as be,sx as bf,f0 as bg,sI as bh,rI as bi,nI as bj,Al as bk,hk as bl,ak as bm,Ol as bn,qi as bo,im as bp,Sp as bq,BE as br,kp as bs,Uo as bt,dk as bu,Dc as bv,mk as bw,vb as bx,K0 as by,nl as bz,pI as c,Dv as c$,wI as c0,PI as c1,jI as c2,N0 as c3,bE as c4,Ss as c5,vI as c6,jE as c7,yI as c8,SI as c9,CS as cA,AS as cB,tl as cC,Lo as cD,xm as cE,IR as cF,xR as cG,DE as cH,ME as cI,NE as cJ,$E as cK,LE as cL,Sk as cM,wr as cN,Cu as cO,eI as cP,Eo as cQ,tE as cR,NR as cS,qd as cT,pb as cU,_s as cV,TE as cW,CE as cX,Dm as cY,nE as cZ,UR as c_,BI as ca,GI as cb,WI as cc,zI as cd,tS as ce,HI as cf,ZI as cg,JS as ch,gI as ci,cx as cj,lx as ck,KI as cl,qE as cm,B_ as cn,wk as co,tx as cp,ES as cq,ex as cr,cI as cs,aI as ct,Pu as cu,ju as cv,pk as cw,fk as cx,cl as cy,Fn as cz,xe as d,L_ as d$,ob as d0,Xd as d1,sb as d2,Mc as d3,SE as d4,E0 as d5,xE as d6,aE as d7,rk as d8,sk as d9,zE as dA,KE as dB,QE as dC,yk as dD,bk as dE,Ve as dF,yb as dG,_0 as dH,Cl as dI,rx as dJ,dI as dK,$o as dL,lI as dM,Ou as dN,y0 as dO,Do as dP,ik as dQ,va as dR,Uh as dS,ok as dT,xp as dU,ZR as dV,VR as dW,tk as dX,nk as dY,zR as dZ,Ud as d_,_k as da,o as db,QI as dc,Ut as dd,Qt as de,gi as df,uI as dg,JE as dh,c0 as di,Mu as dj,Jb as dk,iS as dl,WE as dm,Wo as dn,qI as dp,Bg as dq,Fi as dr,pr as ds,tw as dt,fw as du,rn as dv,Su as dw,ZE as dx,Kw as dy,vu as dz,hI as e,Zk as e$,hd as e0,Uu as e1,Ql as e2,Gh as e3,ck as e4,TR as e5,AR as e6,$R as e7,LR as e8,jR as e9,_R as eA,cy as eB,Vs as eC,gR as eD,fy as eE,uR as eF,nR as eG,lR as eH,wR as eI,tR as eJ,dR as eK,pR as eL,kR as eM,SR as eN,fR as eO,rR as eP,sR as eQ,iR as eR,oR as eS,aR as eT,cR as eU,bR as eV,Rp as eW,Ep as eX,Ip as eY,Tm as eZ,Bl as e_,mn as ea,uk as eb,gk as ec,lk as ed,Ll as ee,en as ef,Ot as eg,qk as eh,eR as ei,Jk as ej,Qk as ek,Wk as el,Jl as em,Kk as en,Uk as eo,Fk as ep,Gk as eq,RR as er,Fm as es,Yk as et,uy as eu,yR as ev,cd as ew,vR as ex,hR as ey,mR as ez,d0 as f,Yl as f0,Zl as f1,Mk as f2,wa as f3,Ho as f4,sS as f5,Hk as f6,bg as f7,Vk as f8,Xk as f9,BR as fA,lr as fB,ao as fC,ym as fD,_m as fE,bp as fF,Ek as fG,xk as fH,Ya as fI,Rk as fJ,kk as fK,Ik as fL,Il as fM,Tk as fN,Ck as fO,EE as fP,FR as fQ,WR as fR,GR as fS,HR as fT,kE as fU,RE as fV,Ak as fW,hp as fX,ba as fY,zk as fa,kg as fb,Pk as fc,Vm as fd,Dk as fe,Nk as ff,$k as fg,Lk as fh,Bk as fi,ER as fj,QR as fk,KR as fl,Q_ as fm,XR as fn,YR as fo,JR as fp,qR as fq,Ok as fr,jk as fs,ps as ft,to as fu,vi as fv,Pp as fw,rw as fx,MR as fy,Xs as fz,ro as g,_u as h,Bp as i,Gp as j,Hp as k,Wp as l,YI as m,XE as n,Eb as o,XS as p,ze as q,p0 as r,IE as s,AE as t,aw as u,db as v,cb as w,ox as x,Ne as y,oS as z};
|