@redocly/replay 0.28.0 → 0.29.0-next.1

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.
Files changed (57) hide show
  1. package/dist/replay-AiChatProvider-B1_-wlJK.js +6 -0
  2. package/dist/{replay-AiChatProvider-DUVoLgY2.js → replay-AiChatProvider-Z_799APd.js} +62 -58
  3. package/dist/{replay-AiChatSqliteDBStorage-C5AnRloD.js → replay-AiChatSqliteDBStorage-B9waB0dA.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-0evx56pl.js → replay-AiChatSqliteDBStorage-C_-_P0T7.js} +1 -1
  5. package/dist/{replay-AiPanel-CMjVD12K.js → replay-AiPanel-DvSoNrnz.js} +4 -4
  6. package/dist/{replay-AiPanel-PVgJioX3.js → replay-AiPanel-IRetnmbM.js} +1 -1
  7. package/dist/replay-FileWatcher-CUqV5dPp.js +1 -0
  8. package/dist/{replay-FileWatcher-CFYprlWN.js → replay-FileWatcher-CZZXT8GC.js} +4 -3
  9. package/dist/{replay-SemanticSearchService-Bh5xYa91.js → replay-SemanticSearchService-B8R-ATMA.js} +1 -1
  10. package/dist/{replay-SemanticSearchService-CulKCCNl.js → replay-SemanticSearchService-BzE8FK8a.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-Bz0muHEk.js → replay-SqliteDBStorage-CPOEQnSp.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-CVHRAsPD.js → replay-SqliteDBStorage-DVQZek3n.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-B163-f2D.js → replay-TauriFileSystemAdapter-BfE1TXkK.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-D4bOmvzP.js → replay-TauriFileSystemAdapter-Zb6LTS_-.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-CjWUrnWz.js → replay-TauriRootStorage-BY7MGWGe.js} +1 -1
  16. package/dist/{replay-TauriRootStorage-2MPQE-3f.js → replay-TauriRootStorage-CUGppZsY.js} +2 -2
  17. package/dist/{replay-agent-loop-DYDFXAZj.js → replay-agent-loop-BB-UIrKo.js} +1 -1
  18. package/dist/{replay-agent-loop-BgYyBo9e.js → replay-agent-loop-BxPUGZq1.js} +3 -3
  19. package/dist/{replay-ai-chat-mappers-BEwNRQPV.js → replay-ai-chat-mappers-C4L8p2zl.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-CMtNqQHX.js → replay-ai-chat-mappers-DAyPOhQn.js} +1 -1
  21. package/dist/{replay-create-model-B2ZsGTjs.js → replay-create-model-BnoDQ7OX.js} +3 -3
  22. package/dist/{replay-create-model-DPxfOEfv.js → replay-create-model-ebcSRl3r.js} +3 -3
  23. package/dist/{replay-db-D4-LmLRk.js → replay-db-og5UtVrp.js} +1 -1
  24. package/dist/{replay-db-C9iqyMet.js → replay-db-xD_5VGuR.js} +1 -1
  25. package/dist/{replay-external-resolver-CTUbNZGW.js → replay-external-resolver-1bxcPBye.js} +1 -1
  26. package/dist/{replay-external-resolver-BXgVrfzk.js → replay-external-resolver-DtqY6Ddl.js} +2 -2
  27. package/dist/{replay-index-4TEahAPK.js → replay-index-C33Z16Rm.js} +16568 -16427
  28. package/dist/{replay-index-DcC173cC.js → replay-index-C7MCjO6i.js} +1 -1
  29. package/dist/{replay-index-Bdg7noSD.js → replay-index-Clfun2IN.js} +1 -1
  30. package/dist/{replay-index-Nz5obVS5.js → replay-index-LcDbGH39.js} +1090 -1077
  31. package/dist/{replay-index-B4U7iZuq.js → replay-index-PEthMsJx.js} +5 -5
  32. package/dist/replay-index-_srgnXqd.js +4 -0
  33. package/dist/{replay-index-B8O3wYqo.js → replay-index-rbCwID24.js} +1 -1
  34. package/dist/{replay-index-q63USe25.js → replay-index-wPsTqXSf.js} +1 -1
  35. package/dist/{replay-lint-s7ylMBWz.js → replay-lint-CVXT7IME.js} +3 -3
  36. package/dist/{replay-lint-4XFKTmSY.js → replay-lint-fhGv2lgR.js} +3 -3
  37. package/dist/{replay-lint-graphql-De2eDZnT.js → replay-lint-graphql-BhMbXKkF.js} +1 -1
  38. package/dist/{replay-lint-graphql-BsBWkZ6L.js → replay-lint-graphql-DtQhF_PM.js} +1 -1
  39. package/dist/{replay-periodic-revalidation-DJbblUef.js → replay-periodic-revalidation-Cuzq23M8.js} +1 -1
  40. package/dist/{replay-periodic-revalidation-BMFP7f-u.js → replay-periodic-revalidation-KHXYhF4T.js} +1 -1
  41. package/dist/{replay-resolve-BtNxNrKo.js → replay-resolve-C0VBozxM.js} +1 -1
  42. package/dist/{replay-resolve-BueEsOnR.js → replay-resolve-C2l91lf8.js} +1 -1
  43. package/dist/{replay-respect-run-Dfpbcsns.js → replay-respect-run-B25T_yI0.js} +3 -3
  44. package/dist/{replay-respect-run-B_dJjlti.js → replay-respect-run-BN4jlLVY.js} +1 -1
  45. package/dist/{replay-tauri-path-Bht3XIt7.js → replay-tauri-path-9tVlry3g.js} +1 -1
  46. package/dist/{replay-tauri-path-CiuYXh_j.js → replay-tauri-path-DpnuyiYr.js} +2 -2
  47. package/dist/{replay-useAiChatQueries-02CRdEPJ.js → replay-useAiChatQueries-Bi_6G8WU.js} +1 -1
  48. package/dist/{replay-useAiChatQueries-D2hh5omV.js → replay-useAiChatQueries-DLSFwWvn.js} +4 -4
  49. package/dist/{replay-validate-key-ALwOF1Ux.js → replay-validate-key-BQB45O00.js} +1 -1
  50. package/dist/{replay-validate-key-B7fbWbfv.js → replay-validate-key-DnQefCz3.js} +2 -2
  51. package/dist/replay.cjs +1 -1
  52. package/dist/replay.d.ts +13 -1
  53. package/dist/replay.js +1 -1
  54. package/package.json +2 -2
  55. package/dist/replay-AiChatProvider-BRqjyy2W.js +0 -6
  56. package/dist/replay-FileWatcher-DGLwO5Kd.js +0 -1
  57. package/dist/replay-index-CG9VN2JQ.js +0 -4
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),a=require("./replay-index-LcDbGH39.js"),te=require("./replay-create-model-BnoDQ7OX.js"),fe=require("./replay-agent-loop-BB-UIrKo.js"),pe=require("./replay-db-xD_5VGuR.js"),v=require("./replay-useAiChatQueries-Bi_6G8WU.js"),B=require("@tanstack/react-query"),Z=require("./replay-ai-chat-mappers-DAyPOhQn.js");class ge{handlers=new Map;middlewares;constructor(t){this.middlewares=t?.middlewares??[]}register(t){this.handlers.set(t.name,t)}getToolSet(){const t={};for(const[n,s]of this.handlers)t[n]=this.buildTool(s);return t}buildTool(t){return{...t.definition,execute:this.wrapExecutor(t)}}wrapExecutor(t){const n=(o,r)=>({isError:!0,error:{message:o,details:r}}),s=this.applyMiddlewares(t.name,t.execute);return(o,r)=>{if(r.abortSignal?.aborted)return n("Tool execution was aborted.");try{const l=s(o,r);return typeof l=="object"&&l!==null&&"then"in l?l.then(u=>u,u=>n(u instanceof Error?u.message:"Unknown tool execution error")):l}catch(l){return n(l instanceof Error?l.message:"Unknown tool execution error")}}}applyMiddlewares(t,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((s,o)=>o(t,s),n)}}function ce(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){const n=Z.buildPersistableUiChat(t);await a.AiChatServiceFactory.getInstance().upsert(n)},onSuccess(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(t){console.error("Failed to upsert ai chat item:",t)}})}function Ce(e){const t=B.useQueryClient(),n=a.aiChatKeys.detailTitle(e??"");return B.useMutation({mutationKey:n,async mutationFn(s){if(t.isMutating({mutationKey:n,exact:!0})>1)return;const o=Z.buildPersistableUiChat(s);await a.AiChatServiceFactory.getInstance().upsert(o)},onSuccess(){t.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(s){console.error("Failed to upsert ai chat item:",s)}})}function me(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){await a.AiChatServiceFactory.getInstance().remove(t)},onMutate:async t=>{await e.cancelQueries({queryKey:a.aiChatKeys.all()});const n=e.getQueryData(a.aiChatKeys.all());n&&e.setQueryData(a.aiChatKeys.all(),n.filter(s=>s.id!==t)),e.setQueryData(a.aiChatKeys.detail(t),null),e.setQueriesData({queryKey:a.aiChatKeys.infiniteHistories()},s=>s&&{...s,pages:s.pages.map(o=>({...o,items:o.items.filter(r=>r.id!==t)}))})},onError(t){console.error("Failed to remove ai chat:",t)},onSettled(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})}})}var ee,oe;function ve(){if(oe)return ee;oe=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let s,o=0;return function(...l){clearTimeout(s);const u=Date.now(),p=u-o,h=n-p;h<=0?(o=u,t.apply(this,l)):s=setTimeout(()=>{o=Date.now(),t.apply(this,l)},h)}}return ee=e,ee}var we=ve();const Ie=a.getDefaultExportFromCjs(we);var ue=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},d=(e,t,n)=>(ue(e,t,"read from private field"),n?n.call(e):t.get(e)),A=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},R=(e,t,n,s)=>(ue(e,t,"write to private field"),t.set(e,n),n);function Te(e,t){return t!=null?Ie(e,t):e}var T,Y,J,j,Q,V,W,ne,se,ye=class{constructor(e=[]){A(this,T,void 0),A(this,Y,"ready"),A(this,J,void 0),A(this,j,new Set),A(this,Q,new Set),A(this,V,new Set),this.pushMessage=t=>{R(this,T,d(this,T).concat(t)),d(this,W).call(this)},this.popMessage=()=>{R(this,T,d(this,T).slice(0,-1)),d(this,W).call(this)},this.replaceMessage=(t,n)=>{R(this,T,[...d(this,T).slice(0,t),this.snapshot(n),...d(this,T).slice(t+1)]),d(this,W).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const s=n?Te(t,n):t;return d(this,j).add(s),()=>{d(this,j).delete(s)}},this["~registerStatusCallback"]=t=>(d(this,Q).add(t),()=>{d(this,Q).delete(t)}),this["~registerErrorCallback"]=t=>(d(this,V).add(t),()=>{d(this,V).delete(t)}),A(this,W,()=>{d(this,j).forEach(t=>t())}),A(this,ne,()=>{d(this,Q).forEach(t=>t())}),A(this,se,()=>{d(this,V).forEach(t=>t())}),R(this,T,e)}get status(){return d(this,Y)}set status(e){R(this,Y,e),d(this,ne).call(this)}get error(){return d(this,J)}set error(e){R(this,J,e),d(this,se).call(this)}get messages(){return d(this,T)}set messages(e){R(this,T,[...e]),d(this,W).call(this)}};T=new WeakMap;Y=new WeakMap;J=new WeakMap;j=new WeakMap;Q=new WeakMap;V=new WeakMap;W=new WeakMap;ne=new WeakMap;se=new WeakMap;var U,ae=class extends te.AbstractChat{constructor({messages:e,...t}){const n=new ye(e);super({...t,state:n}),A(this,U,void 0),this["~registerMessagesCallback"]=(s,o)=>d(this,U)["~registerMessagesCallback"](s,o),this["~registerStatusCallback"]=s=>d(this,U)["~registerStatusCallback"](s),this["~registerErrorCallback"]=s=>d(this,U)["~registerErrorCallback"](s),R(this,U,n)}};U=new WeakMap;function Ae({experimental_throttle:e,resume:t=!1,...n}={}){const s=i.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const o={...n,onToolCall:c=>{var g,f;return(f=(g=s.current).onToolCall)==null?void 0:f.call(g,c)},onData:c=>{var g,f;return(f=(g=s.current).onData)==null?void 0:f.call(g,c)},onFinish:c=>{var g,f;return(f=(g=s.current).onFinish)==null?void 0:f.call(g,c)},onError:c=>{var g,f;return(f=(g=s.current).onError)==null?void 0:f.call(g,c)},sendAutomaticallyWhen:c=>{var g,f,_;return(_=(f=(g=s.current).sendAutomaticallyWhen)==null?void 0:f.call(g,c))!=null?_:!1}},r=i.useRef("chat"in n?n.chat:new ae(o));("chat"in n&&n.chat!==r.current||"id"in n&&n.id!=null&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new ae(o));const u=i.useCallback(c=>r.current["~registerMessagesCallback"](c,e),[e,r.current.id]),p=i.useSyncExternalStore(u,()=>r.current.messages,()=>r.current.messages),h=i.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),w=i.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),I=i.useCallback(c=>{typeof c=="function"&&(c=c(r.current.messages)),r.current.messages=c},[r]);return i.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:p,setMessages:I,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:w,resumeStream:r.current.resumeStream,status:h,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput,addToolApprovalResponse:r.current.addToolApprovalResponse}}const be=20;function Se(e){if(e.length===0)return"No OpenAPI specs loaded.";const t=e.slice(0,be),n=t.map(ke),s=e.length-t.length;return s>0&&n.push(` …and ${s} more API(s) not shown.`),[`Loaded APIs (${e.length}):`,...n].join(`
2
+ `)}function ke(e){return[` apiId="${e.apiId}"`,`title="${e.title}"`,e.version?`version="${e.version}"`:null,e.primaryServer?`server="${e.primaryServer}"`:null].filter(Boolean).join(" ")}const Ee=30;function Me(e){if(e.length===0)return"No Arazzo collections loaded.";const t=[`Arazzo collections (${e.length}):`];let n=Ee,s=0,o=0;for(const l of e){if(n<=0){s+=l.workflows.length,o++;continue}if(t.push(Re(l)),n--,l.workflows.length===0)t.push(" (no workflows)");else if(n>=2){t.push(` workflows (${l.workflows.length}):`),n--;for(const u of l.workflows)n>0?(t.push(` ${_e(u)}`),n--):s++}else s+=l.workflows.length}const r=[s>0?`${s} more workflow(s)`:null,o>0?`${o} more collection(s)`:null].filter(Boolean);return r.length>0&&t.push(` …and ${r.join(", plus ")} not shown.`),t.join(`
3
+ `)}function Re(e){const t=e.sourceApiIds.length>0?` apis=[${e.sourceApiIds.join(", ")}]`:"";return` collectionId="${e.collectionId}" title="${e.title}"${t}`}function _e(e){const t=`id="${e.workflowId}"`,n=e.summary?`label="${e.summary}"`:null,s=`[${e.stepCount} step${e.stepCount!==1?"s":""}]`;return[t,n,s].filter(Boolean).join(" ")}const Pe=20;function De(e){if(e.length===0)return"No environments configured.";const t=e.slice(0,Pe),n=t.map(xe),s=e.length-t.length;return s>0&&n.push(` …and ${s} more environment(s) not shown.`),[`Environments (${e.length}); * marks the active environment:`,...n].join(`
4
+ `)}function xe(e){return[`${e.isActive?"*":" "} name="${e.name}"`,`inputs=${e.inputCount}`,`servers=${e.serverCount}`].join(" ")}const $e=30;function Oe(e){if(e.length===0)return"No tabs are open.";const t=e.slice(0,$e),n=t.map(We),s=e.length-t.length;return s>0&&n.push(` …and ${s} more tab(s) not shown.`),[`Open tabs (${e.length}), listed by tabIndex; * marks the active (focused) tab:`,...n].join(`
5
+ `)}function We(e){const t=[e.collectionId?`collectionId="${e.collectionId}"`:null,e.workflowId?`workflowId="${e.workflowId}"`:null,e.stepId?`stepId="${e.stepId}"`:null,e.operationId?`operationId="${e.operationId}"`:null].filter(Boolean),n=[e.isPreview?"preview":null,e.isDraft?"draft":null,e.isHistory?"history":null].filter(Boolean);return[`${e.isActive?"*":" "} ${e.tabIndex}.`,`type="${e.type}"`,`label="${e.label}"`,...t,n.length>0?`(${n.join(", ")})`:null].filter(Boolean).join(" ")}const Ue="Auto-attached snapshot of the user's current Replay UI state. Generated by Replay before each step; not written by the user. It is a shallow summary — use tools to read detailed tab contents when needed.";function Be(e){const t=`
6
+ `.repeat(2),n=[Ue,t,Oe(e.tabs),t,Se(e.apis),t,Me(e.collections),t,De(e.environments)].join("");return pe.section("active_state",n)}function Le(e){return e.map(Fe)}function Fe(e){return{apiId:e.id,title:e.info?.title??"Untitled API",version:e.info?.version,primaryServer:e.servers?.[0]?.url}}function Ne(e){return e.map(qe)}function qe(e){const t=(e.workflows??[]).map(s=>({workflowId:s.workflowId,summary:s.summary,stepCount:s.steps?.length??0})),n=(e.sourceDescriptions??[]).map(s=>s.apiId).filter(Boolean);return{collectionId:e.id,title:e.info?.title??"Untitled Collection",workflows:t,sourceApiIds:n}}function Ke(e,t){return e.filter(n=>n.state!==a.ItemState.Draft).map(n=>({name:n.name,isActive:n.name===t,inputCount:n.inputs.length,serverCount:n.servers.length}))}function je(e,t,n){return e.map((s,o)=>Qe(n,s,o,o===t))}function Qe(e,t,n,s){const o={tabIndex:n,type:t.data.type,isActive:s,isPreview:t.state===a.TabState.Preview};switch(t.data.type){case a.TabDataType.Collection:{const{collectionId:r}=t.data;return{...o,label:Ve(e,r)??r,collectionId:r}}case a.TabDataType.Workflow:{const{collectionId:r,workflowId:l}=t.data;return{...o,label:l,collectionId:r,workflowId:l}}case a.TabDataType.WorkflowRun:{const{collectionId:r,workflowId:l,historyId:u,label:p}=t.data;return{...o,label:p??`${l} run`,collectionId:r,workflowId:l,isHistory:u!=null}}case a.TabDataType.Step:{const r=t.data;return{...o,label:He(r),collectionId:r.collectionId,workflowId:r.workflowId,stepId:r.stepId,operationId:r.draftStep?.operation?.operationId??null,isDraft:!r.collectionId&&!r.workflowId,isHistory:r.historyId!=null}}}}function Ve(e,t){return e.find(n=>n.id===t)?.info.title}function He(e){if(e.stepId)return e.stepId;if(e.draftStep){const t=[a.getStepMethod(e.draftStep),a.getStepUrl(e.draftStep)].filter(Boolean).join(" ");if(t)return t}return"New Request"}function Ge(e){const t=e.get(a.collectionsAtom);return{tabs:je(e.get(a.tabsAtom),e.get(a.activeTabIdxAtom),t),apis:Le(e.get(a.apisAtom)),collections:Ne(t),environments:Ke(e.get(a.environmentsAtom),e.get(a.activeEnvironmentIdAtom))}}function ze(){const e=a.useCollections(),{tab:t}=a.useActiveTab(),n=t?.data??null;return i.useMemo(()=>{if(!n)return null;switch(n.type){case a.TabDataType.Collection:{const o=a.findCollection(e,n.collectionId);return{...n,collection:o}}case a.TabDataType.Workflow:{const o=a.findWorkflow(e,{collectionId:n.collectionId,workflowId:n.workflowId});return{...n,workflow:o}}case a.TabDataType.Step:{const o=a.findStep(e,{collectionId:n.collectionId,workflowId:n.workflowId,stepId:n.stepId});return{...n,step:o}}case a.TabDataType.WorkflowRun:{const o=a.findWorkflow(e,{collectionId:n.collectionId,workflowId:n.workflowId});return{...n,workflow:o}}}},[n,e])}function Ye(e){if(!e||typeof e!="object"||!("changes"in e)||!Array.isArray(e.changes))return e;const t=e.changes.filter(s=>s&&typeof s=="object"&&"approved"in s&&s.approved===!0),n="meta"in e&&typeof e.meta=="object"?e.meta:{};return{...e,changes:t,meta:{...n,totalChanges:e.changes.length,approvedChanges:t.length}}}function Je(){return(e,t)=>(n,s)=>t(Ye(n),s)}function Xe(){const{getApiOperation:e}=a.useApiOperationGetter(),t=a.useTabHandlers();return i.useMemo(()=>({getApiOperation:e,...t}),[e,t])}function Ze(e){const{convertOperationToReplayValue:t}=a.useSettingsContext(),n=ze(),s=Xe(),o=a.useSettings(),r=a.useStore(),{attachApiToCollection:l}=a.useCollectionActions(),{handleCloseByDataId:u}=a.useTabHandlers(),p=a.useRunWorkflow(),h=i.useRef(n);return h.current=n,{tools:i.useMemo(()=>{const I=new ge({middlewares:[Je()]});return v.registerBuiltInTools(I,{[v.reportStatusBlueprint.name]:void 0,[v.runRequestBlueprint.name]:{settings:o,store:r},[v.runWorkflowBlueprint.name]:{store:r,runWorkflow:p},[v.updateSecurityBlueprint.name]:{store:r},[v.updateStepBlueprint.name]:{store:r},[v.manageCollectionBlueprint.name]:{store:r,attachApiToCollection:l,handleCloseByDataId:u,convertOperationToReplayValue:t},[v.manageEnvironmentBlueprint.name]:{store:r},[v.webSearchBlueprint.name]:{model:e},[v.searchBlueprint.name]:{store:r},[v.openTabBlueprint.name]:{store:r,context:s},[v.getCurrentTabBlueprint.name]:{getActiveTabDetailedData:()=>h.current},[v.getApiMetadataBlueprint.name]:{store:r}}),I.getToolSet()},[l,t,u,e,s,p,o,r])}}function et(e){const{children:t,chatId:n,model:s,initialMessages:o,onChatFinish:r,onChatMessagesUpdated:l}=e,u=a.useSettings(),{getReuniteAuth:p}=a.useSettingsContext(),{tools:h}=Ze(s),{sendEvent:w}=a.useTelemetry(),I=i.useRef(h),c=i.useRef(s),{isOpen:g,openPanel:f,closePanel:_}=a.useAiPanel(),P=i.useRef(void 0),L=a.useStore();I.current=h,c.current=s;const C=i.useMemo(()=>{P.current?.end();const E=a.trace.getTracer("replay-ai-chat").startSpan("ai.chat.session",{attributes:{conversation_id:n}});P.current=E;const M=a.trace.setSpan(a.context.active(),E);return new fe.AgentLoop({activeConversationId:n,model:c.current,tools:I.current,sendEvent:w,parentCtx:M,getActiveStateMessage:()=>Be(Ge(L))})},[n,w,L]);i.useEffect(()=>()=>P.current?.end(),[]);const x=i.useMemo(()=>{if(C)return new te.DirectChatTransport({agent:C.getAgent()})},[C]);i.useEffect(()=>{C.setModel(s)},[C,s]),i.useEffect(()=>{C.registerTools(h)},[C,h]);const{messages:S,setMessages:D,sendMessage:F,status:k,error:H,stop:$,addToolApprovalResponse:N}=Ae({id:n,messages:o,transport:x,sendAutomaticallyWhen:te.lastAssistantMessageIsCompleteWithApprovalResponses,onFinish(E){if(!r||!C)return;r({agentLoop:C,chat:this},E)}}),b=i.useMemo(()=>k==="streaming"||k==="submitted",[k]),q=i.useCallback(()=>{u.aiEnabled===!0&&f()},[f,u.aiEnabled]),K=i.useCallback(()=>{_()},[_]),G=i.useCallback(async E=>{const M=E.trim();if(!(!M||!x)){if(s.provider===a.REUNITE_AI_PROVIDER){const y=await p?.();y?.baseUrl&&y?.accessToken&&C.setModel({provider:a.REUNITE_AI_PROVIDER,baseUrl:y.baseUrl,accessToken:y.accessToken})}D(y=>v.hasPendingApprovalMessage(y)?v.denyPendingApprovals(y):y),F({text:M})}},[C,p,s.provider,F,D,x]),m=i.useCallback(()=>{b&&$()},[b,$]);i.useEffect(()=>()=>{$()},[n,$]);const O=i.useCallback(E=>{const M=E(S),y=M.map(z=>z.message),re=[...S];for(const z of M)re[z.index]=z.message;D(re),l?.(y)},[S,l,D]),de=i.useMemo(()=>({messages:S,isStreaming:b,chatStatus:k,chatError:H,sendMessage:G,updateMessages:O,stopGeneration:m,addToolApprovalResponse:N}),[N,H,b,S,G,k,m,O]),he=i.useMemo(()=>({isOpen:g,openPanel:q,closePanel:K}),[g,q,K]);return X.jsx(v.AiConversationContext.Provider,{value:de,children:X.jsx(a.AiPanelContext.Provider,{value:he,children:t})})}function tt(e){return e.slice(-2)}function nt(e,t){return!!(e||t<1)}function st(e){return i.useCallback(async(t,n)=>{if(nt(e,n.messages.length))return null;const s=n.messages[0],o=v.getMessageTextContent(s.parts);try{return(await t.agentLoop.generateTitle(o)).trim()}catch(r){return console.error("Unable to generate chat title",r),null}},[e])}function rt({chatId:e,model:t,existingTitle:n}){const{mutate:s}=Ce(e),o=st(n);return i.useCallback(async(...r)=>{const l=await o(...r);l!==null&&l.length!==0&&s({id:e,model:t,messages:[],title:l})},[o,t,e,s])}function ot({chatId:e,model:t}){const{mutate:n}=ce();return i.useCallback((s,o)=>{const r=tt(o.messages);n({id:e,model:t,messages:r})},[t,e,n])}function at({chatId:e,model:t}){const{mutate:n}=ce();return i.useCallback(s=>{s.length!==0&&n({id:e,model:t,messages:s})},[t,e,n])}function it(e){return i.useMemo(()=>{const t=[a.REUNITE_MODEL_OPTION];if(e){for(const[n,s]of Object.entries(e))if(s.enabled&&s.apiKey){const o=s.models.map(r=>({...r,provider:n}));t.push(...o)}}return t},[e])}function ie(e){return typeof e=="function"?e():e}function le(e,t){try{const n=globalThis.localStorage.getItem(e);return n===null?ie(t):n}catch{return ie(t)}}function lt(e,t){try{globalThis.localStorage.setItem(e,t)}catch{console.error("Failed to write to localStorage",{key:e,value:t})}}function ct(e,t){const[n,s]=i.useState(()=>le(e,t)),o=i.useRef(t);o.current=t,i.useEffect(()=>{s(le(e,o.current))},[e]);const r=i.useCallback(l=>{s(u=>{const p=l instanceof Function?l(u):l;return lt(e,p),p})},[e]);return[n,r]}const ut="replay:ai:selectedModelId";function dt(e){const{availableModels:t,aiProviders:n,reuniteAuth:s}=e,[o,r]=ct(ut,a.REUNITE_MODEL_OPTION.id),l=t.some(p=>p.id===o)?o:a.REUNITE_MODEL_OPTION.id;return{model:i.useMemo(()=>{const p={provider:a.REUNITE_AI_PROVIDER,baseUrl:s.baseUrl,accessToken:s.accessToken},h=t.find(I=>I.id===l);if(!h||h.provider===a.REUNITE_AI_PROVIDER)return p;const w=n?.[h.provider];return!w||!w.apiKey||!w.enabled?p:{provider:h.provider,modelId:h.id,apiKey:w.apiKey}},[l,t,n,s]),selectedModelId:l,selectModel:r}}function ht(){const[e,t]=i.useState({baseUrl:"",accessToken:""}),{getReuniteAuth:n}=a.useSettingsContext();return i.useEffect(()=>{let s=!1;async function o(){const r=await n?.();s||t({baseUrl:r?.baseUrl??"",accessToken:r?.accessToken??""})}return o().catch(()=>{s||t({baseUrl:"",accessToken:""})}),()=>{s=!0}},[n]),e}function ft(e){const{children:t}=e,[n,s]=i.useState(Z.generateAiChatId),[o,r]=i.useState(n),[l,u]=i.useState(null),p=a.useSettings(),h=a.useSettingsContext(),{openPanel:w}=a.useAiPanel(),I=o!==n,c=i.useCallback(()=>{const m=Z.generateAiChatId();r(m),s(m)},[]),g=i.useCallback(m=>{r(m)},[]),{data:f}=v.useAiChat(o),_=ht(),P=it(h.aiProviders),{selectedModelId:L,model:C,selectModel:x}=dt({availableModels:P,aiProviders:h.aiProviders,reuniteAuth:_}),S=me(),D=ot({chatId:n,model:C}),F=at({chatId:n,model:C}),k=rt({chatId:n,model:C,existingTitle:f?.title}),H=i.useCallback((m,O)=>{O.isAbort||(D(m,O),k(m,O))},[D,k]),$=i.useCallback((...m)=>{F(...m)},[F]),N=i.useCallback(m=>{(o===m||n===m)&&c(),S.mutate(m)},[c,n,S,o]),b=f?.id;i.useEffect(()=>{b&&b!==n&&s(b)},[b,o,n]);const q=i.useCallback(()=>{u(null)},[]),K=i.useCallback(m=>{p.aiEnabled&&(c(),u(m),w())},[w,c,p.aiEnabled]),G=i.useMemo(()=>({chatId:n,model:C,availableModels:P,selectedModelId:L,selectModel:x,onSettingsOpen:h.onSettingsOpen,title:f?.title??a.defaultAiChatContextValue.title,isLoading:I,selectChat:g,removeChat:N,createNewChat:c,openAiChatWithPresetInput:K,pendingComposerPreset:l,clearPendingComposerPreset:q}),[n,P,f?.title,C,I,g,N,c,K,l,q,L,x,h.onSettingsOpen]);return X.jsx(a.AiChatContext.Provider,{value:G,children:X.jsx(et,{chatId:n,model:C,initialMessages:f?.messages,onChatFinish:H,onChatMessagesUpdated:$,children:t})})}exports.AiChatProvider=ft;
@@ -1,12 +1,12 @@
1
1
  import { jsx as te } from "react/jsx-runtime";
2
2
  import { useRef as W, useCallback as f, useSyncExternalStore as re, useEffect as R, useMemo as I, useState as z } from "react";
3
- import { a0 as S, a1 as ce, K as _e, a2 as Re, a3 as $e, a4 as $, a5 as Pe, a6 as xe, c as De, a7 as We, a8 as Be, a as Oe, a9 as Ue, aa as Fe, ab as Le, ac as je, ad as fe, ae as Ne, af as Ke, ag as qe, ah as Ae, ai as se, aj as ue, ak as Te, al as Qe, am as Ve, an as Ge, ao as ye, z as ge, B as He, R as ne, ap as ze, aq as ae, ar as Ye, as as Je } from "./replay-index-4TEahAPK.js";
4
- import { A as Xe, D as Ze, l as et } from "./replay-create-model-DPxfOEfv.js";
5
- import { AgentLoop as tt } from "./replay-agent-loop-BgYyBo9e.js";
6
- import { s as nt } from "./replay-db-D4-LmLRk.js";
7
- import { r as st, g as rt, a as ot, o as at, s as it, w as lt, m as ct, b as ut, u as dt, c as ht, d as pt, e as ft, f as gt, h as mt, i as vt, A as wt, j as Ct, k as It } from "./replay-useAiChatQueries-D2hh5omV.js";
3
+ import { a0 as S, a1 as ce, K as _e, a2 as Re, a3 as $e, a4 as $, a5 as Pe, a6 as xe, c as De, a7 as We, a8 as Be, a as Oe, a9 as Ue, aa as Fe, ab as Le, ac as je, ad as fe, ae as Ne, af as Ke, ag as qe, ah as Ae, ai as se, aj as ue, ak as Te, al as Qe, am as Ve, an as Ge, ao as ye, z as ge, B as He, R as ne, ap as ze, aq as ae, ar as Ye, as as Je } from "./replay-index-C33Z16Rm.js";
4
+ import { A as Xe, D as Ze, l as et } from "./replay-create-model-ebcSRl3r.js";
5
+ import { AgentLoop as tt } from "./replay-agent-loop-BxPUGZq1.js";
6
+ import { s as nt } from "./replay-db-og5UtVrp.js";
7
+ import { r as st, g as rt, a as ot, o as at, s as it, w as lt, m as ct, b as ut, u as dt, c as ht, d as pt, e as ft, f as gt, h as mt, i as vt, A as wt, j as Ct, k as It } from "./replay-useAiChatQueries-DLSFwWvn.js";
8
8
  import { useQueryClient as de, useMutation as he } from "@tanstack/react-query";
9
- import { d as Se, g as me } from "./replay-ai-chat-mappers-BEwNRQPV.js";
9
+ import { d as Se, g as me } from "./replay-ai-chat-mappers-C4L8p2zl.js";
10
10
  class At {
11
11
  handlers = /* @__PURE__ */ new Map();
12
12
  middlewares;
@@ -39,9 +39,9 @@ class At {
39
39
  try {
40
40
  const a = s(o, r);
41
41
  return typeof a == "object" && a !== null && "then" in a ? a.then(
42
- (i) => i,
43
- (i) => n(
44
- i instanceof Error ? i.message : "Unknown tool execution error"
42
+ (l) => l,
43
+ (l) => n(
44
+ l instanceof Error ? l.message : "Unknown tool execution error"
45
45
  )
46
46
  ) : a;
47
47
  } catch (a) {
@@ -128,8 +128,8 @@ function St() {
128
128
  let s, o = 0;
129
129
  return function(...a) {
130
130
  clearTimeout(s);
131
- const i = Date.now(), h = i - o, u = n - h;
132
- u <= 0 ? (o = i, t.apply(this, a)) : s = setTimeout(() => {
131
+ const l = Date.now(), h = l - o, u = n - h;
132
+ u <= 0 ? (o = l, t.apply(this, a)) : s = setTimeout(() => {
133
133
  o = Date.now(), t.apply(this, a);
134
134
  }, u);
135
135
  };
@@ -237,37 +237,37 @@ function _t({
237
237
  });
238
238
  const o = {
239
239
  ...n,
240
- onToolCall: (l) => {
240
+ onToolCall: (i) => {
241
241
  var p, d;
242
- return (d = (p = s.current).onToolCall) == null ? void 0 : d.call(p, l);
242
+ return (d = (p = s.current).onToolCall) == null ? void 0 : d.call(p, i);
243
243
  },
244
- onData: (l) => {
244
+ onData: (i) => {
245
245
  var p, d;
246
- return (d = (p = s.current).onData) == null ? void 0 : d.call(p, l);
246
+ return (d = (p = s.current).onData) == null ? void 0 : d.call(p, i);
247
247
  },
248
- onFinish: (l) => {
248
+ onFinish: (i) => {
249
249
  var p, d;
250
- return (d = (p = s.current).onFinish) == null ? void 0 : d.call(p, l);
250
+ return (d = (p = s.current).onFinish) == null ? void 0 : d.call(p, i);
251
251
  },
252
- onError: (l) => {
252
+ onError: (i) => {
253
253
  var p, d;
254
- return (d = (p = s.current).onError) == null ? void 0 : d.call(p, l);
254
+ return (d = (p = s.current).onError) == null ? void 0 : d.call(p, i);
255
255
  },
256
- sendAutomaticallyWhen: (l) => {
256
+ sendAutomaticallyWhen: (i) => {
257
257
  var p, d, P;
258
- return (P = (d = (p = s.current).sendAutomaticallyWhen) == null ? void 0 : d.call(p, l)) != null ? P : !1;
258
+ return (P = (d = (p = s.current).sendAutomaticallyWhen) == null ? void 0 : d.call(p, i)) != null ? P : !1;
259
259
  }
260
260
  }, r = W(
261
261
  "chat" in n ? n.chat : new we(o)
262
262
  );
263
263
  ("chat" in n && n.chat !== r.current || "id" in n && n.id != null && r.current.id !== n.id) && (r.current = "chat" in n ? n.chat : new we(o));
264
- const i = f(
265
- (l) => r.current["~registerMessagesCallback"](l, e),
264
+ const l = f(
265
+ (i) => r.current["~registerMessagesCallback"](i, e),
266
266
  // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
267
267
  // eslint-disable-next-line react-hooks/exhaustive-deps
268
268
  [e, r.current.id]
269
269
  ), h = re(
270
- i,
270
+ l,
271
271
  () => r.current.messages,
272
272
  () => r.current.messages
273
273
  ), u = re(
@@ -279,8 +279,8 @@ function _t({
279
279
  () => r.current.error,
280
280
  () => r.current.error
281
281
  ), w = f(
282
- (l) => {
283
- typeof l == "function" && (l = l(r.current.messages)), r.current.messages = l;
282
+ (i) => {
283
+ typeof i == "function" && (i = i(r.current.messages)), r.current.messages = i;
284
284
  },
285
285
  [r]
286
286
  );
@@ -336,8 +336,8 @@ function Dt(e) {
336
336
  t.push(" (no workflows)");
337
337
  else if (n >= 2) {
338
338
  t.push(` workflows (${a.workflows.length}):`), n--;
339
- for (const i of a.workflows)
340
- n > 0 ? (t.push(` ${Bt(i)}`), n--) : s++;
339
+ for (const l of a.workflows)
340
+ n > 0 ? (t.push(` ${Bt(l)}`), n--) : s++;
341
341
  } else
342
342
  s += a.workflows.length;
343
343
  }
@@ -480,13 +480,13 @@ function Jt(e, t, n, s) {
480
480
  return { ...o, label: a, collectionId: r, workflowId: a };
481
481
  }
482
482
  case $.WorkflowRun: {
483
- const { collectionId: r, workflowId: a, historyId: i, label: h } = t.data;
483
+ const { collectionId: r, workflowId: a, historyId: l, label: h } = t.data;
484
484
  return {
485
485
  ...o,
486
486
  label: h ?? `${a} run`,
487
487
  collectionId: r,
488
488
  workflowId: a,
489
- isHistory: i != null
489
+ isHistory: l != null
490
490
  };
491
491
  }
492
492
  case $.Step: {
@@ -535,40 +535,44 @@ function tn() {
535
535
  if (!n)
536
536
  return null;
537
537
  switch (n.type) {
538
- case $.Collection:
538
+ case $.Collection: {
539
539
  const o = Ke(e, n.collectionId);
540
540
  return {
541
541
  ...n,
542
542
  collection: o
543
543
  };
544
- case $.Workflow:
545
- const r = fe(e, {
544
+ }
545
+ case $.Workflow: {
546
+ const o = fe(e, {
546
547
  collectionId: n.collectionId,
547
548
  workflowId: n.workflowId
548
549
  });
549
550
  return {
550
551
  ...n,
551
- workflow: r
552
+ workflow: o
552
553
  };
553
- case $.Step:
554
- const a = Ne(e, {
554
+ }
555
+ case $.Step: {
556
+ const o = Ne(e, {
555
557
  collectionId: n.collectionId,
556
558
  workflowId: n.workflowId,
557
559
  stepId: n.stepId
558
560
  });
559
561
  return {
560
562
  ...n,
561
- step: a
563
+ step: o
562
564
  };
563
- case $.WorkflowRun:
564
- const i = fe(e, {
565
+ }
566
+ case $.WorkflowRun: {
567
+ const o = fe(e, {
565
568
  collectionId: n.collectionId,
566
569
  workflowId: n.workflowId
567
570
  });
568
571
  return {
569
572
  ...n,
570
- workflow: i
573
+ workflow: o
571
574
  };
575
+ }
572
576
  }
573
577
  }, [n, e]);
574
578
  }
@@ -602,7 +606,7 @@ function rn() {
602
606
  );
603
607
  }
604
608
  function on(e) {
605
- const { convertOperationToReplayValue: t } = se(), n = tn(), s = rn(), o = ue(), r = Te(), { attachApiToCollection: a } = Qe(), { handleCloseByDataId: i } = Ae(), h = Ve(), u = W(n);
609
+ const { convertOperationToReplayValue: t } = se(), n = tn(), s = rn(), o = ue(), r = Te(), { attachApiToCollection: a } = Qe(), { handleCloseByDataId: l } = Ae(), h = Ve(), u = W(n);
606
610
  return u.current = n, { tools: I(() => {
607
611
  const w = new At({
608
612
  middlewares: [sn()]
@@ -616,7 +620,7 @@ function on(e) {
616
620
  [ut.name]: {
617
621
  store: r,
618
622
  attachApiToCollection: a,
619
- handleCloseByDataId: i,
623
+ handleCloseByDataId: l,
620
624
  convertOperationToReplayValue: t
621
625
  },
622
626
  [ct.name]: { store: r },
@@ -631,7 +635,7 @@ function on(e) {
631
635
  }, [
632
636
  a,
633
637
  t,
634
- i,
638
+ l,
635
639
  e,
636
640
  s,
637
641
  h,
@@ -640,8 +644,8 @@ function on(e) {
640
644
  ]) };
641
645
  }
642
646
  function an(e) {
643
- const { children: t, chatId: n, model: s, initialMessages: o, onChatFinish: r, onChatMessagesUpdated: a } = e, i = ue(), { getReuniteAuth: h } = se(), { tools: u } = on(s), { sendEvent: v } = Ge(), w = W(u), l = W(s), { isOpen: p, openPanel: d, closePanel: P } = ye(), x = W(void 0), j = Te();
644
- w.current = u, l.current = s;
647
+ const { children: t, chatId: n, model: s, initialMessages: o, onChatFinish: r, onChatMessagesUpdated: a } = e, l = ue(), { getReuniteAuth: h } = se(), { tools: u } = on(s), { sendEvent: v } = Ge(), w = W(u), i = W(s), { isOpen: p, openPanel: d, closePanel: P } = ye(), x = W(void 0), j = Te();
648
+ w.current = u, i.current = s;
645
649
  const g = I(() => {
646
650
  x.current?.end();
647
651
  const M = ge.getTracer("replay-ai-chat").startSpan("ai.chat.session", { attributes: { conversation_id: n } });
@@ -649,7 +653,7 @@ function an(e) {
649
653
  const E = ge.setSpan(He.active(), M);
650
654
  return new tt({
651
655
  activeConversationId: n,
652
- model: l.current,
656
+ model: i.current,
653
657
  tools: w.current,
654
658
  sendEvent: v,
655
659
  parentCtx: E,
@@ -684,8 +688,8 @@ function an(e) {
684
688
  r({ agentLoop: g, chat: this }, M);
685
689
  }
686
690
  }), y = I(() => b === "streaming" || b === "submitted", [b]), q = f(() => {
687
- i.aiEnabled === !0 && d();
688
- }, [d, i.aiEnabled]), Q = f(() => {
691
+ l.aiEnabled === !0 && d();
692
+ }, [d, l.aiEnabled]), Q = f(() => {
689
693
  P();
690
694
  }, [P]), J = f(
691
695
  async (M) => {
@@ -860,8 +864,8 @@ function mn(e, t) {
860
864
  }, [e]);
861
865
  const r = f(
862
866
  (a) => {
863
- s((i) => {
864
- const h = a instanceof Function ? a(i) : a;
867
+ s((l) => {
868
+ const h = a instanceof Function ? a(l) : a;
865
869
  return gn(e, h), h;
866
870
  });
867
871
  },
@@ -916,7 +920,7 @@ function Cn() {
916
920
  }, [n]), e;
917
921
  }
918
922
  function _n(e) {
919
- const { children: t } = e, [n, s] = z(me), [o, r] = z(n), [a, i] = z(null), h = ue(), u = se(), { openPanel: v } = ye(), w = o !== n, l = f(() => {
923
+ const { children: t } = e, [n, s] = z(me), [o, r] = z(n), [a, l] = z(null), h = ue(), u = se(), { openPanel: v } = ye(), w = o !== n, i = f(() => {
920
924
  const m = me();
921
925
  r(m), s(m);
922
926
  }, []), p = f((m) => {
@@ -941,20 +945,20 @@ function _n(e) {
941
945
  [N]
942
946
  ), K = f(
943
947
  (m) => {
944
- (o === m || n === m) && l(), k.mutate(m);
948
+ (o === m || n === m) && i(), k.mutate(m);
945
949
  },
946
- [l, n, k, o]
950
+ [i, n, k, o]
947
951
  ), y = d?.id;
948
952
  R(() => {
949
953
  y && y !== n && s(y);
950
954
  }, [y, o, n]);
951
955
  const q = f(() => {
952
- i(null);
956
+ l(null);
953
957
  }, []), Q = f(
954
958
  (m) => {
955
- h.aiEnabled && (l(), i(m), v());
959
+ h.aiEnabled && (i(), l(m), v());
956
960
  },
957
- [v, l, h.aiEnabled]
961
+ [v, i, h.aiEnabled]
958
962
  ), J = I(
959
963
  () => ({
960
964
  chatId: n,
@@ -967,7 +971,7 @@ function _n(e) {
967
971
  isLoading: w,
968
972
  selectChat: p,
969
973
  removeChat: K,
970
- createNewChat: l,
974
+ createNewChat: i,
971
975
  openAiChatWithPresetInput: Q,
972
976
  pendingComposerPreset: a,
973
977
  clearPendingComposerPreset: q
@@ -980,7 +984,7 @@ function _n(e) {
980
984
  w,
981
985
  p,
982
986
  K,
983
- l,
987
+ i,
984
988
  Q,
985
989
  a,
986
990
  q,
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-CMtNqQHX.js"),s=require("./replay-indexes-Dqjl8m6C.js"),c={orderBy:[s.asc(i.aiMessages.createdAt),s.asc(i.aiMessages.indexWithinInsertBatch)],with:{parts:{orderBy:[s.asc(i.aiMessageParts.index)]}}};class g{constructor(e){this.sqliteDB=e}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:c}})).map(h.convertAiChatRowToUiChat)}async findRecentChatsPage(e){await this.initialize();const a=e.limit+1,r=await this.db.query.aiChats.findMany({orderBy:(d,{desc:o})=>o(d.updatedAt),limit:a,offset:e.offset}),t=r.slice(0,e.limit),n=r.length>e.limit,w=e.offset+t.length;return{items:t.map(d=>{const o={...d,messages:[]};return h.convertAiChatRowToUiChat(o)}),hasMore:n,nextOffset:w}}async findOne(e){await this.initialize();const a=await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,e),with:{messages:c}});return a&&h.convertAiChatRowToUiChat(a)}async upsert(e){await this.initialize();const a=h.convertUiChatToAiChatRow(e);await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,a.id),columns:{id:!0}})?await this.db.update(i.aiChats).set(a).where(s.eq(i.aiChats.id,a.id)):await this.db.insert(i.aiChats).values(a);for(let t=0;t<e.messages.length;t++)await this.upsertMessageRowAndParts(e.id,t,e.messages[t])}async remove(e){await this.initialize(),await this.db.delete(i.aiChats).where(s.eq(i.aiChats.id,e))}async upsertMessageRowAndParts(e,a,r){const t=await this.db.query.aiMessages.findFirst({where:s.and(s.eq(i.aiMessages.aiChatId,e),s.eq(i.aiMessages.uiId,r.id))}),n=h.convertUiMessageToAiChatMessage(e,a,r,t?.id);t?await this.db.update(i.aiMessages).set({...n,indexWithinInsertBatch:t.indexWithinInsertBatch}).where(s.eq(i.aiMessages.id,t.id)):await this.db.insert(i.aiMessages).values(n),await this.db.delete(i.aiMessageParts).where(s.eq(i.aiMessageParts.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(i.aiMessageParts).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}exports.AiChatSqliteDBStorage=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-DAyPOhQn.js"),s=require("./replay-indexes-Dqjl8m6C.js"),c={orderBy:[s.asc(i.aiMessages.createdAt),s.asc(i.aiMessages.indexWithinInsertBatch)],with:{parts:{orderBy:[s.asc(i.aiMessageParts.index)]}}};class g{constructor(e){this.sqliteDB=e}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:c}})).map(h.convertAiChatRowToUiChat)}async findRecentChatsPage(e){await this.initialize();const a=e.limit+1,r=await this.db.query.aiChats.findMany({orderBy:(d,{desc:o})=>o(d.updatedAt),limit:a,offset:e.offset}),t=r.slice(0,e.limit),n=r.length>e.limit,w=e.offset+t.length;return{items:t.map(d=>{const o={...d,messages:[]};return h.convertAiChatRowToUiChat(o)}),hasMore:n,nextOffset:w}}async findOne(e){await this.initialize();const a=await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,e),with:{messages:c}});return a&&h.convertAiChatRowToUiChat(a)}async upsert(e){await this.initialize();const a=h.convertUiChatToAiChatRow(e);await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,a.id),columns:{id:!0}})?await this.db.update(i.aiChats).set(a).where(s.eq(i.aiChats.id,a.id)):await this.db.insert(i.aiChats).values(a);for(let t=0;t<e.messages.length;t++)await this.upsertMessageRowAndParts(e.id,t,e.messages[t])}async remove(e){await this.initialize(),await this.db.delete(i.aiChats).where(s.eq(i.aiChats.id,e))}async upsertMessageRowAndParts(e,a,r){const t=await this.db.query.aiMessages.findFirst({where:s.and(s.eq(i.aiMessages.aiChatId,e),s.eq(i.aiMessages.uiId,r.id))}),n=h.convertUiMessageToAiChatMessage(e,a,r,t?.id);t?await this.db.update(i.aiMessages).set({...n,indexWithinInsertBatch:t.indexWithinInsertBatch}).where(s.eq(i.aiMessages.id,t.id)):await this.db.insert(i.aiMessages).values(n),await this.db.delete(i.aiMessageParts).where(s.eq(i.aiMessageParts.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(i.aiMessageParts).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}exports.AiChatSqliteDBStorage=g;
@@ -1,7 +1,7 @@
1
1
  import "./replay-history.schema-B0lLwmdG.js";
2
2
  import "./replay-step-context.schema-BOprzd6Z.js";
3
3
  import { a as h, b as r, c as n } from "./replay-ai-message-parts.schema-DKLf0SiG.js";
4
- import { c, a as u, b as m } from "./replay-ai-chat-mappers-BEwNRQPV.js";
4
+ import { c, a as u, b as m } from "./replay-ai-chat-mappers-C4L8p2zl.js";
5
5
  import { b as l, e, c as b } from "./replay-indexes-B3PJtgeh.js";
6
6
  const g = {
7
7
  orderBy: [l(r.createdAt), l(r.indexWithinInsertBatch)],
@@ -1,13 +1,13 @@
1
1
  import { jsxs as m, jsx as i, Fragment as Ne } from "react/jsx-runtime";
2
2
  import { useCallback as _, useMemo as A, useState as Y, Fragment as ht, useRef as F, useEffect as B, useLayoutEffect as je } from "react";
3
3
  import c, { css as ue } from "styled-components";
4
- import { a3 as be, at as Ce, au as mt, ag as gt, ah as vt, u as yt, av as fe, aw as pe, S as V, ax as xe, ay as xt, az as wt, aA as ke, c as bt, aB as Ct, aC as Ue, aD as kt, aE as Tt, R as he, A as le, aF as We, ao as Ge, aG as we, aH as U, aI as It } from "./replay-index-4TEahAPK.js";
5
- import { l as At, n as St, p as Lt, q as Pt, T as Et, t as Rt, v as Ot, x as Ye, C as I, y as Dt, z as qe, L as Mt, B as Q, D as _t, E as zt, F as Vt, G as $t, H as N } from "./replay-useAiChatQueries-D2hh5omV.js";
4
+ import { a3 as be, at as Ce, au as mt, ag as gt, ah as vt, u as yt, av as fe, aw as pe, S as V, ax as xe, ay as xt, az as wt, aA as ke, c as bt, aB as Ct, aC as Ue, aD as kt, aE as Tt, R as he, A as le, aF as We, ao as Ge, aG as we, aH as U, aI as It } from "./replay-index-C33Z16Rm.js";
5
+ import { l as At, n as St, p as Lt, q as Pt, T as Et, t as Rt, v as Ot, x as Ye, C as I, y as Dt, z as qe, L as Mt, B as Q, D as _t, E as zt, F as Vt, G as $t, H as N } from "./replay-useAiChatQueries-DLSFwWvn.js";
6
6
  import { AI_SEARCH_MAX_MESSAGE_LENGTH as Ht } from "@redocly/theme/core/constants/search";
7
7
  import { Button as P } from "@redocly/theme/components/Button/Button";
8
8
  import { SendIcon as Bt } from "@redocly/theme/icons/SendIcon/SendIcon";
9
9
  import { StopIcon as Ft } from "@redocly/theme/icons/StopIcon/StopIcon";
10
- import { M as z } from "./replay-db-D4-LmLRk.js";
10
+ import { M as z } from "./replay-db-og5UtVrp.js";
11
11
  import { CheckboxIcon as Nt } from "@redocly/theme/icons/CheckboxIcon/CheckboxIcon";
12
12
  import { CheckmarkFilledIcon as jt } from "@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon";
13
13
  import { CloseFilledIcon as Ut } from "@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon";
@@ -25,7 +25,7 @@ import { ChatGptIcon as Qt } from "@redocly/theme/icons/ChatGptIcon/ChatGptIcon"
25
25
  import { GeminiIcon as en } from "@redocly/theme/icons/GeminiIcon/GeminiIcon";
26
26
  import { ClaudeIcon as tn } from "@redocly/theme/icons/ClaudeIcon/ClaudeIcon";
27
27
  import { Tooltip as W } from "@redocly/theme/components/Tooltip/Tooltip";
28
- import { g as Te } from "./replay-SemanticSearchService-Bh5xYa91.js";
28
+ import { g as Te } from "./replay-SemanticSearchService-B8R-ATMA.js";
29
29
  import "@tanstack/react-query";
30
30
  import { Typography as Z } from "@redocly/theme/components/Typography/Typography";
31
31
  import { TrashCanIcon as nn } from "@redocly/theme/icons/TrashCanIcon/TrashCanIcon";
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),h=require("react"),X=require("styled-components"),f=require("./replay-index-Nz5obVS5.js"),x=require("./replay-useAiChatQueries-02CRdEPJ.js"),Ge=require("@redocly/theme/core/constants/search"),E=require("@redocly/theme/components/Button/Button"),Ue=require("@redocly/theme/icons/SendIcon/SendIcon"),We=require("@redocly/theme/icons/StopIcon/StopIcon"),M=require("./replay-db-C9iqyMet.js"),Ye=require("@redocly/theme/icons/CheckboxIcon/CheckboxIcon"),Ke=require("@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon"),Je=require("@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon"),Xe=require("@redocly/theme/icons/AddIcon/AddIcon"),Ze=require("@redocly/theme/icons/SubtractIcon/SubtractIcon"),K=require("@redocly/theme/core/utils"),Qe=require("@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon"),et=require("@redocly/theme/icons/ChevronRightIcon/ChevronRightIcon"),tt=require("@redocly/theme/components/Dropdown/Dropdown"),nt=require("@redocly/theme/components/Dropdown/DropdownMenu"),Ie=require("@redocly/theme/components/Dropdown/DropdownMenuItem"),rt=require("@redocly/theme/icons/CheckmarkIcon/CheckmarkIcon"),ot=require("@redocly/theme/icons/SettingsCogIcon/SettingsCogIcon"),it=require("@redocly/theme/icons/ChatGptIcon/ChatGptIcon"),st=require("@redocly/theme/icons/GeminiIcon/GeminiIcon"),at=require("@redocly/theme/icons/ClaudeIcon/ClaudeIcon"),B=require("@redocly/theme/components/Tooltip/Tooltip"),ae=require("./replay-SemanticSearchService-CulKCCNl.js");require("@tanstack/react-query");const G=require("@redocly/theme/components/Typography/Typography"),lt=require("@redocly/theme/icons/TrashCanIcon/TrashCanIcon"),ct=require("@redocly/theme/icons/AiStarsGradientIcon/AiStarsGradientIcon"),dt=require("@redocly/theme/icons/CloseIcon/CloseIcon"),ut=require("@redocly/theme/icons/NewChatIcon/NewChatIcon"),ft=require("@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon"),pt=require("@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon"),ht=e=>e&&e.__esModule?e:{default:e},l=ht(X);function xt({placeholder:e="Ask anything...",className:t,disabled:n,isStreaming:r=!1,onStop:o,modelSelector:s,value:a,onValueChange:c,onSubmit:d,textareaRef:u}){const p=a.trim(),v=!n&&p.length>0&&!r,g=!n&&p.length>0,w=A=>{c(A.target.value)},m=()=>{!p||n||r||d()},b=()=>{!r||!o||o()},C=A=>{A.key==="Enter"&&!A.shiftKey&&!A.nativeEvent.isComposing&&(A.preventDefault(),r&&o?b():m())};return i.jsxs(gt,{className:t,$isActive:g,children:[i.jsx(vt,{ref:u,rows:1,maxLength:Ge.AI_SEARCH_MAX_MESSAGE_LENGTH,placeholder:e,value:a,disabled:n,spellCheck:!1,onChange:w,onKeyDown:C}),i.jsxs(mt,{children:[s,r&&o?i.jsx(wt,{type:"button",size:"small","aria-label":"Stop generating",icon:i.jsx(We.StopIcon,{color:"var(--icon-color-on-color)"}),onClick:b}):i.jsx(yt,{type:"button",size:"small","aria-label":"Send message",icon:i.jsx(Ue.SendIcon,{color:"var(--icon-color-on-color)"}),onClick:m,disabled:!v})]})]})}const gt=l.default.div`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),h=require("react"),X=require("styled-components"),f=require("./replay-index-LcDbGH39.js"),x=require("./replay-useAiChatQueries-Bi_6G8WU.js"),Ge=require("@redocly/theme/core/constants/search"),E=require("@redocly/theme/components/Button/Button"),Ue=require("@redocly/theme/icons/SendIcon/SendIcon"),We=require("@redocly/theme/icons/StopIcon/StopIcon"),M=require("./replay-db-xD_5VGuR.js"),Ye=require("@redocly/theme/icons/CheckboxIcon/CheckboxIcon"),Ke=require("@redocly/theme/icons/CheckmarkFilledIcon/CheckmarkFilledIcon"),Je=require("@redocly/theme/icons/CloseFilledIcon/CloseFilledIcon"),Xe=require("@redocly/theme/icons/AddIcon/AddIcon"),Ze=require("@redocly/theme/icons/SubtractIcon/SubtractIcon"),K=require("@redocly/theme/core/utils"),Qe=require("@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon"),et=require("@redocly/theme/icons/ChevronRightIcon/ChevronRightIcon"),tt=require("@redocly/theme/components/Dropdown/Dropdown"),nt=require("@redocly/theme/components/Dropdown/DropdownMenu"),Ie=require("@redocly/theme/components/Dropdown/DropdownMenuItem"),rt=require("@redocly/theme/icons/CheckmarkIcon/CheckmarkIcon"),ot=require("@redocly/theme/icons/SettingsCogIcon/SettingsCogIcon"),it=require("@redocly/theme/icons/ChatGptIcon/ChatGptIcon"),st=require("@redocly/theme/icons/GeminiIcon/GeminiIcon"),at=require("@redocly/theme/icons/ClaudeIcon/ClaudeIcon"),B=require("@redocly/theme/components/Tooltip/Tooltip"),ae=require("./replay-SemanticSearchService-BzE8FK8a.js");require("@tanstack/react-query");const G=require("@redocly/theme/components/Typography/Typography"),lt=require("@redocly/theme/icons/TrashCanIcon/TrashCanIcon"),ct=require("@redocly/theme/icons/AiStarsGradientIcon/AiStarsGradientIcon"),dt=require("@redocly/theme/icons/CloseIcon/CloseIcon"),ut=require("@redocly/theme/icons/NewChatIcon/NewChatIcon"),ft=require("@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon"),pt=require("@redocly/theme/icons/ArrowLeftIcon/ArrowLeftIcon"),ht=e=>e&&e.__esModule?e:{default:e},l=ht(X);function xt({placeholder:e="Ask anything...",className:t,disabled:n,isStreaming:r=!1,onStop:o,modelSelector:s,value:a,onValueChange:c,onSubmit:d,textareaRef:u}){const p=a.trim(),v=!n&&p.length>0&&!r,g=!n&&p.length>0,w=A=>{c(A.target.value)},m=()=>{!p||n||r||d()},b=()=>{!r||!o||o()},C=A=>{A.key==="Enter"&&!A.shiftKey&&!A.nativeEvent.isComposing&&(A.preventDefault(),r&&o?b():m())};return i.jsxs(gt,{className:t,$isActive:g,children:[i.jsx(vt,{ref:u,rows:1,maxLength:Ge.AI_SEARCH_MAX_MESSAGE_LENGTH,placeholder:e,value:a,disabled:n,spellCheck:!1,onChange:w,onKeyDown:C}),i.jsxs(mt,{children:[s,r&&o?i.jsx(wt,{type:"button",size:"small","aria-label":"Stop generating",icon:i.jsx(We.StopIcon,{color:"var(--icon-color-on-color)"}),onClick:b}):i.jsx(yt,{type:"button",size:"small","aria-label":"Send message",icon:i.jsx(Ue.SendIcon,{color:"var(--icon-color-on-color)"}),onClick:m,disabled:!v})]})]})}const gt=l.default.div`
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--spacing-xs);
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./replay-index-LcDbGH39.js"),f=require("./replay-SemanticSearchService-BzE8FK8a.js");var v;(function(l){l.WINDOW_RESIZED="tauri://resize",l.WINDOW_MOVED="tauri://move",l.WINDOW_CLOSE_REQUESTED="tauri://close-requested",l.WINDOW_DESTROYED="tauri://destroyed",l.WINDOW_FOCUS="tauri://focus",l.WINDOW_BLUR="tauri://blur",l.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",l.WINDOW_THEME_CHANGED="tauri://theme-changed",l.WINDOW_CREATED="tauri://window-created",l.WEBVIEW_CREATED="tauri://webview-created",l.DRAG_ENTER="tauri://drag-enter",l.DRAG_OVER="tauri://drag-over",l.DRAG_DROP="tauri://drag-drop",l.DRAG_LEAVE="tauri://drag-leave"})(v||(v={}));async function m(l,e){await h.invoke("plugin:event|unlisten",{event:l,eventId:e})}async function E(l,e,i){var s;const n=(s=void 0)!==null&&s!==void 0?s:{kind:"Any"};return h.invoke("plugin:event|listen",{event:l,target:n,handler:h.transformCallback(e)}).then(t=>async()=>m(l,t))}class w{constructor(e,i,s,n,t,o){this.storage=e,this.projectDir=i,this.aiEnabled=s,this.environments=n,this.apis=t,this.collections=o}storage;projectDir;aiEnabled;environments;apis;collections;watchPath=null;unlistenEvent=null;pendingEnvironmentsReload=Promise.resolve();get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexApis(e).catch(i=>console.error("Semantic index (apis):",i))}indexCollections(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexCollections(e).catch(i=>console.error("Semantic index (collections):",i))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeApi(s))).catch(s=>console.error("Semantic remove (apis):",s))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeCollection(s))).catch(s=>console.error("Semantic remove (collections):",s))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await E("fs-watch-event",async e=>{const i=e.payload;try{await this.handleEvent(i)}catch(s){console.error("Error handling file change:",s)}}),await h.invoke("fs_watch",{path:this.projectDir,options:{recursive:!0,delayMs:500}}),this.watchPath=this.projectDir}catch(e){throw console.error("Failed to start file watcher:",e),this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),e}}async stop(){if(this.watchPath)try{await h.invoke("fs_unwatch",{path:this.watchPath})}catch(e){console.error("Error stopping file watcher:",e)}finally{this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),this.watchPath=null}}async handleEvent(e){const{changeType:i,paths:s,pathTypes:n,type:t}=e;if(await this.isProjectFolderRemoved(s,i)){await this.handleProjectFolderRemoval();return}const o=this.filterSpecFiles(s,n);if(o.paths.length===0)return;const a=await this.toFileEntries(o.paths,o.pathTypes);switch(i){case"changed":{(t.includes("Data")||t.includes("Name"))&&await this.handleModify(a);break}case"added":await this.handleCreate(a);break;case"deleted":await this.handleDelete(a);break;case"renamed":await this.handleRename(a);break;default:console.log("Unhandled change type:",i)}}filterSpecFiles(e,i){const s=[],n=[];for(let t=0;t<e.length;t++){const o=e[t],a=o.split(".").pop()?.toLowerCase();a&&["yaml","yml","json"].includes(a)&&(s.push(o),n.push(i[t]||"unknown"))}return{paths:s,pathTypes:n}}async toFileEntries(e,i){return Promise.all(e.map(async(s,n)=>({relative_path:await h.PathUtils.relative(this.projectDir,s),absolute_path:s,type:i[n]||"unknown"})))}hasExternalConfigChange(e){return e.some(i=>h.isRedoclyConfigFile(i.relative_path)&&!this.storage.isWatchExcluded(i.relative_path))}withoutConfigFile(e){return e.filter(i=>!h.isRedoclyConfigFile(i.relative_path))}consolidateFileEntries(e){const i=[],s=new Set;for(const n of e)s.has(n.relative_path)||(s.add(n.relative_path),this.storage.isWatchExcluded(n.relative_path)||i.push(n));return i}async handleModify(e){const i=this.hasExternalConfigChange(e),s=this.withoutConfigFile(e),{newApiFiles:n,existingApiFiles:t}=this.categorizeApisFromFiles(s),{newCollectionFiles:o,existingCollectionFiles:a}=this.categorizeCollectionsFromFiles(s),c=await this.findApisToReload(e),r=await this.findCollectionsToReload(e),p=[...n,...o];p.length>0&&await this.handleCreate(p),i&&await this.reloadEnvironments();const u=this.consolidateFileEntries([...t,...c]),g=this.consolidateFileEntries([...a,...r]);await this.reloadApis(u),await this.reloadCollections(g)}async handleCreate(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=i.filter(r=>r.type==="api"),n=i.filter(r=>r.type==="collection"),{newApiFiles:t,existingApiFiles:o}=this.categorizeApisFromFiles(s),{newCollectionFiles:a,existingCollectionFiles:c}=this.categorizeCollectionsFromFiles(n);if(t.length>0||a.length>0){t.forEach(d=>this.storage.addPersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.addPersistExcludedId(d.relative_path));const r=t.length>0?await this.tauriStorage.loadAndParseApis(t,void 0,!0):[],p=a.length>0?await this.tauriStorage.loadAndParseCollections(a,void 0):[],u=r.filter(d=>d!==null),g=p.filter(d=>d!==null);this.apis.set([...this.apis.get(),...u]),this.collections.set([...this.collections.get(),...g]),this.indexApis(u),this.indexCollections(g),setTimeout(()=>{t.forEach(d=>this.storage.removePersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.removePersistExcludedId(d.relative_path))},500)}o.length>0&&await this.reloadApis(o),c.length>0&&await this.reloadCollections(c)}categorizeApisFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.apis.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="api"&&s.push(t)}return{newApiFiles:s,existingApiFiles:n}}categorizeCollectionsFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.collections.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="collection"&&s.push(t)}return{newCollectionFiles:s,existingCollectionFiles:n}}async handleDelete(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=[],n=[];for(const t of i){this.storage.addPersistExcludedId(t.relative_path);const o=this.apis.get();o.some(r=>r.id===t.relative_path)&&(this.apis.set(o.filter(r=>r.id!==t.relative_path)),this.tauriStorage.deleteApiFromCache(t.relative_path),s.push(t.relative_path));const a=this.collections.get(),c=a.findIndex(r=>r.id===t.relative_path);c>=0&&(this.collections.set(a.filter((r,p)=>p!==c)),n.push(t.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(t.relative_path)},500)}this.removeApis(s),this.removeCollections(n)}async handleRename(e){if(e.length>=2){const[i,s]=e;await this.handleDelete([i]),await this.handleCreate([s])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,i){if(e.length===0)return!1;if(i==="deleted"||i==="renamed"){for(const n of e)if(n===this.projectDir)return!0}return e.filter(n=>!n.startsWith(this.projectDir+"/")&&n!==this.projectDir).length>0&&i==="renamed"}async handleProjectFolderRemoval(){const e=this.apis.get(),i=e.map(t=>t.id);e.forEach(t=>{this.storage.addPersistExcludedId(t.id),this.tauriStorage.deleteApiFromCache(t.id)}),this.apis.set([]);const s=this.collections.get(),n=s.map(t=>t.id);s.forEach(t=>{this.storage.addPersistExcludedId(t.id)}),this.collections.set([]),setTimeout(()=>{e.forEach(t=>this.storage.removePersistExcludedId(t.id)),s.forEach(t=>this.storage.removePersistExcludedId(t.id))},500),this.removeApis(i),this.removeCollections(n),await this.stop()}async findApisToReload(e){const i=[];return await Promise.all(this.apis.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"api"})}})),i}async findCollectionsToReload(e){const i=[];return await Promise.all(this.collections.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"collection"})}})),i}reloadEnvironments(){const e=this.pendingEnvironmentsReload.then(()=>this.readAndPublishEnvironments());return this.pendingEnvironmentsReload=e.catch(()=>{}),e}async readAndPublishEnvironments(){const e=this.environments.get(),i=await this.tauriStorage.readEnvironments();!(this.environments.get()!==e)&&(i.length>0||!this.storage.getEnvironmentsConfigError())&&this.environments.set(i.length>0?i:h.cloneObject(h.DEFAULT_ENVIRONMENTS)),this.storage.publishEnvironmentsConfigError()}async reloadApis(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseApis(e,void 0,!0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.apis.get();o.some(a=>a.id===n.id)?(this.storage.addPersistExcludedId(n.id),this.apis.set(o.map(a=>a.id===n.id?n:a)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("API not found in state after reload:",n.id)})),s.length>0&&this.indexApis(s)}async reloadCollections(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseCollections(e,void 0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.collections.get(),a=o.findIndex(c=>c.id===n.id);a>=0?(this.storage.addPersistExcludedId(n.id),this.collections.set(o.map((c,r)=>r===a?n:c)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("Collection not found in state after reload:",n.id)})),s.length>0&&this.indexCollections(s)}}exports.FileWatcher=w;
@@ -1,5 +1,5 @@
1
- import { i as f, t as w, P as m, q as v, u as C, D as F } from "./replay-index-4TEahAPK.js";
2
- import { g } from "./replay-SemanticSearchService-Bh5xYa91.js";
1
+ import { i as f, t as w, P as m, q as v, u as C, D as F } from "./replay-index-C33Z16Rm.js";
2
+ import { g } from "./replay-SemanticSearchService-B8R-ATMA.js";
3
3
  var E;
4
4
  (function(l) {
5
5
  l.WINDOW_RESIZED = "tauri://resize", l.WINDOW_MOVED = "tauri://move", l.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", l.WINDOW_DESTROYED = "tauri://destroyed", l.WINDOW_FOCUS = "tauri://focus", l.WINDOW_BLUR = "tauri://blur", l.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", l.WINDOW_THEME_CHANGED = "tauri://theme-changed", l.WINDOW_CREATED = "tauri://window-created", l.WEBVIEW_CREATED = "tauri://webview-created", l.DRAG_ENTER = "tauri://drag-enter", l.DRAG_OVER = "tauri://drag-over", l.DRAG_DROP = "tauri://drag-drop", l.DRAG_LEAVE = "tauri://drag-leave";
@@ -109,9 +109,10 @@ class P {
109
109
  return;
110
110
  const a = await this.toFileEntries(o.paths, o.pathTypes);
111
111
  switch (i) {
112
- case "changed":
112
+ case "changed": {
113
113
  (t.includes("Data") || t.includes("Name")) && await this.handleModify(a);
114
114
  break;
115
+ }
115
116
  case "added":
116
117
  await this.handleCreate(a);
117
118
  break;
@@ -1,4 +1,4 @@
1
- import { i as f, I as W, J as X, y } from "./replay-index-4TEahAPK.js";
1
+ import { i as f, I as W, J as X, y } from "./replay-index-C33Z16Rm.js";
2
2
  import { O as z } from "./replay-Observable-D6wKbFwB.js";
3
3
  import { p as K } from "./replay-promise-map-limit-Db_42GvV.js";
4
4
  function w(t) {
@@ -1 +1 @@
1
- "use strict";const d=require("./replay-index-Nz5obVS5.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function z(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function te(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(ne(o,i))}return n}function ne(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function ie(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function oe(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?U(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function ae(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=U(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=te(i,r),h=ie(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...se.filter(u=>u in a),...re.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function le(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function W(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function Q(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function X(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=pe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(R)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(R),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await Z.promiseMapLimit(n,ue,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=K(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=de(s,i);return o.indexDocuments(r,fe)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;
1
+ "use strict";const d=require("./replay-index-LcDbGH39.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function z(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function te(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(ne(o,i))}return n}function ne(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function ie(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function oe(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?U(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function ae(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=U(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=te(i,r),h=ie(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...se.filter(u=>u in a),...re.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function le(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function W(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function Q(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function X(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=pe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(R)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(R),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await Z.promiseMapLimit(n,ue,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=K(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=de(s,i);return o.indexDocuments(r,fe)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;
@@ -1,4 +1,4 @@
1
- import { i as Qe } from "./replay-index-4TEahAPK.js";
1
+ import { i as Qe } from "./replay-index-C33Z16Rm.js";
2
2
  import { h as Ve } from "./replay-history.schema-B0lLwmdG.js";
3
3
  import { s as Ue } from "./replay-step-context.schema-BOprzd6Z.js";
4
4
  import { b as J, c as X, a as ee } from "./replay-ai-message-parts.schema-DKLf0SiG.js";