@redocly/replay 0.27.1 → 0.28.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 (54) hide show
  1. package/dist/{replay-AiChatProvider-Cdve_kxz.js → replay-AiChatProvider-COJYrrQ6.js} +6 -6
  2. package/dist/{replay-AiChatProvider-IuOVaWMC.js → replay-AiChatProvider-DjEmmTbN.js} +1 -1
  3. package/dist/{replay-AiChatSqliteDBStorage-jEhfZgK3.js → replay-AiChatSqliteDBStorage-BenAoLmM.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-B3aaY0Uo.js → replay-AiChatSqliteDBStorage-CBeRerfX.js} +1 -1
  5. package/dist/{replay-AiPanel-BT_RLVeR.js → replay-AiPanel-BN1uduZr.js} +37 -37
  6. package/dist/{replay-AiPanel-0GXuobhF.js → replay-AiPanel-FAJJA4QT.js} +1 -1
  7. package/dist/replay-FileWatcher-DDlINC06.js +1 -0
  8. package/dist/replay-FileWatcher-paEMsDuu.js +352 -0
  9. package/dist/{replay-SemanticSearchService--QXHzf7_.js → replay-SemanticSearchService-DwIcsNYC.js} +1 -1
  10. package/dist/{replay-SemanticSearchService-DJ_jBUyi.js → replay-SemanticSearchService-OutwGWqD.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-0JYq0UPY.js → replay-SqliteDBStorage-Cn8L_KB1.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-ClD7MBeX.js → replay-SqliteDBStorage-CrB-WSIX.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-BnSXgnQc.js → replay-TauriFileSystemAdapter-CocGBrH_.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-BuHbmM-L.js → replay-TauriFileSystemAdapter-q89YsNXx.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-B1vFT2Rg.js → replay-TauriRootStorage-CZXVp2Zw.js} +1 -1
  16. package/dist/{replay-TauriRootStorage-D6K0MuWv.js → replay-TauriRootStorage-DHVdmo5Z.js} +5 -3
  17. package/dist/{replay-agent-loop-jUYXZfye.js → replay-agent-loop-cbxVIXnO.js} +9 -9
  18. package/dist/{replay-agent-loop-X2MrvEk-.js → replay-agent-loop-vzQUCpCA.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-B0Ay6VKi.js → replay-ai-chat-mappers-BnAf2rpg.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-sgE5XiwA.js → replay-ai-chat-mappers-pb8lpkUD.js} +1 -1
  21. package/dist/{replay-create-model-DB6xE5Ap.js → replay-create-model-CqA612v0.js} +3 -3
  22. package/dist/{replay-create-model-NrGYVueM.js → replay-create-model-Dr80k74P.js} +4 -4
  23. package/dist/{replay-db-BZNR8xEd.js → replay-db-Bq7IGfIa.js} +1 -1
  24. package/dist/{replay-db-BiP6dME4.js → replay-db-C8RC-t2R.js} +1 -1
  25. package/dist/{replay-external-resolver-PLyV0HZs.js → replay-external-resolver-Bw7R-LTs.js} +1 -1
  26. package/dist/{replay-external-resolver-DPAdPRks.js → replay-external-resolver-D6WP4NJY.js} +2 -2
  27. package/dist/{replay-index-yAV5TCua.js → replay-index-B3sCvU48.js} +1 -1
  28. package/dist/{replay-index-HHtp5T42.js → replay-index-BFdS3tY7.js} +1 -1
  29. package/dist/{replay-index-B2RZCGOF.js → replay-index-BizzVzWT.js} +22420 -21604
  30. package/dist/{replay-index-DTD47ryK.js → replay-index-CI5L8ebr.js} +1 -1
  31. package/dist/{replay-index-D85qPcEF.js → replay-index-D3evrr0U.js} +1205 -1098
  32. package/dist/{replay-index-DDUSidTx.js → replay-index-DZwTSW3m.js} +2 -2
  33. package/dist/{replay-index-DmAVD_C4.js → replay-index-DsAn0c_r.js} +1 -1
  34. package/dist/{replay-index-DKNhWzy4.js → replay-index-bspotqBs.js} +5 -5
  35. package/dist/{replay-lint-DyUeemr_.js → replay-lint-D5d7AeDU.js} +3 -3
  36. package/dist/{replay-lint-graphql-D_p-TkyV.js → replay-lint-graphql-CYl9hbRz.js} +1 -1
  37. package/dist/{replay-lint-graphql-pt1vf5MX.js → replay-lint-graphql-C_f79j2l.js} +1 -1
  38. package/dist/{replay-lint-Bico-a-1.js → replay-lint-q7b2-PPR.js} +3 -3
  39. package/dist/{replay-resolve-CQzlNcS2.js → replay-resolve-CftMmcPx.js} +1 -1
  40. package/dist/{replay-resolve-IKJYgmPW.js → replay-resolve-Km_DObpf.js} +1 -1
  41. package/dist/{replay-respect-run-CtDn7oS8.js → replay-respect-run-CfbJ-uak.js} +3 -3
  42. package/dist/{replay-respect-run-rx_nPWZM.js → replay-respect-run-DBe6ZUcc.js} +1 -1
  43. package/dist/{replay-tauri-path-iA6pF5e0.js → replay-tauri-path-BrtMOZvF.js} +1 -1
  44. package/dist/{replay-tauri-path-DrwBKGJP.js → replay-tauri-path-Ek8BSAa0.js} +2 -2
  45. package/dist/{replay-useAiChatQueries-PECgHJpT.js → replay-useAiChatQueries-BR1eEjUB.js} +4 -4
  46. package/dist/{replay-useAiChatQueries-BIZfilWh.js → replay-useAiChatQueries-DjjzEorX.js} +1 -1
  47. package/dist/{replay-validate-key-CvZaTfXj.js → replay-validate-key-CZSwxFid.js} +2 -2
  48. package/dist/{replay-validate-key-CTJn216O.js → replay-validate-key-Cox-cRT6.js} +1 -1
  49. package/dist/replay.cjs +1 -1
  50. package/dist/replay.d.ts +9 -0
  51. package/dist/replay.js +6 -6
  52. package/package.json +2 -2
  53. package/dist/replay-FileWatcher-CtHVgewC.js +0 -343
  54. package/dist/replay-FileWatcher-NkpXJA-C.js +0 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./replay-index-D85qPcEF.js"),Y=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-BuHbmM-L.js");var U={exports:{}},V;function oe(){return V||(V=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(a,u,f){this.fn=a,this.context=u,this.once=f||!1}function o(a,u,f,l,g){if(typeof f!="function")throw new TypeError("The listener must be a function");var y=new n(f,l||a,g),m=t?t+u:u;return a._events[m]?a._events[m].fn?a._events[m]=[a._events[m],y]:a._events[m].push(y):(a._events[m]=y,a._eventsCount++),a}function d(a,u){--a._eventsCount===0?a._events=new r:delete a._events[u]}function h(){this._events=new r,this._eventsCount=0}h.prototype.eventNames=function(){var u=[],f,l;if(this._eventsCount===0)return u;for(l in f=this._events)e.call(f,l)&&u.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(f)):u},h.prototype.listeners=function(u){var f=t?t+u:u,l=this._events[f];if(!l)return[];if(l.fn)return[l.fn];for(var g=0,y=l.length,m=new Array(y);g<y;g++)m[g]=l[g].fn;return m},h.prototype.listenerCount=function(u){var f=t?t+u:u,l=this._events[f];return l?l.fn?1:l.length:0},h.prototype.emit=function(u,f,l,g,y,m){var b=t?t+u:u;if(!this._events[b])return!1;var c=this._events[b],T=arguments.length,Q,w;if(c.fn){switch(c.once&&this.removeListener(u,c.fn,void 0,!0),T){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,f),!0;case 3:return c.fn.call(c.context,f,l),!0;case 4:return c.fn.call(c.context,f,l,g),!0;case 5:return c.fn.call(c.context,f,l,g,y),!0;case 6:return c.fn.call(c.context,f,l,g,y,m),!0}for(w=1,Q=new Array(T-1);w<T;w++)Q[w-1]=arguments[w];c.fn.apply(c.context,Q)}else{var ae=c.length,x;for(w=0;w<ae;w++)switch(c[w].once&&this.removeListener(u,c[w].fn,void 0,!0),T){case 1:c[w].fn.call(c[w].context);break;case 2:c[w].fn.call(c[w].context,f);break;case 3:c[w].fn.call(c[w].context,f,l);break;case 4:c[w].fn.call(c[w].context,f,l,g);break;default:if(!Q)for(x=1,Q=new Array(T-1);x<T;x++)Q[x-1]=arguments[x];c[w].fn.apply(c[w].context,Q)}}return!0},h.prototype.on=function(u,f,l){return o(this,u,f,l,!1)},h.prototype.once=function(u,f,l){return o(this,u,f,l,!0)},h.prototype.removeListener=function(u,f,l,g){var y=t?t+u:u;if(!this._events[y])return this;if(!f)return d(this,y),this;var m=this._events[y];if(m.fn)m.fn===f&&(!g||m.once)&&(!l||m.context===l)&&d(this,y);else{for(var b=0,c=[],T=m.length;b<T;b++)(m[b].fn!==f||g&&!m[b].once||l&&m[b].context!==l)&&c.push(m[b]);c.length?this._events[y]=c.length===1?c[0]:c:d(this,y)}return this},h.prototype.removeAllListeners=function(u){var f;return u?(f=t?t+u:u,this._events[f]&&d(this,f)):(this._events=new r,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,s.exports=h})(U)),U.exports}var ue=oe();const le=p.getDefaultExportFromCjs(ue);class re extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ce=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const J=s=>globalThis.DOMException===void 0?new ce(s):new DOMException(s),H=s=>{const e=s.reason===void 0?J("This operation was aborted."):s.reason;return e instanceof Error?e:J(e)};function he(s,e,t,r){let n;const o=new Promise((d,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){d(s);return}if(r={customTimers:{setTimeout,clearTimeout},...r},r.signal){const{signal:a}=r;a.aborted&&h(H(a)),a.addEventListener("abort",()=>{h(H(a))})}n=r.customTimers.setTimeout.call(void 0,()=>{const a=`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(a);typeof s.cancel=="function"&&s.cancel(),h(u)},e),(async()=>{try{d(await s)}catch(a){h(a)}finally{r.customTimers.clearTimeout.call(void 0,n)}})()});return o.clear=()=>{clearTimeout(n),n=void 0},o}function fe(s,e,t){let r=0,n=s.length;for(;n>0;){const o=Math.trunc(n/2);let d=r+o;t(s[d],e)<=0?(r=++d,n-=o+1):n=o}return r}var F=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},A;class de{constructor(){A.set(this,[])}enqueue(e,t){t={priority:0,...t};const r={priority:t.priority,run:e};if(this.size&&F(this,A,"f")[this.size-1].priority>=t.priority){F(this,A,"f").push(r);return}const n=fe(F(this,A,"f"),r,(o,d)=>d.priority-o.priority);F(this,A,"f").splice(n,0,r)}dequeue(){const e=F(this,A,"f").shift();return e?.run}filter(e){return F(this,A,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return F(this,A,"f").length}}A=new WeakMap;var v=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},i=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},_,L,M,I,R,N,z,E,O,P,k,S,W,C,q,X,Z,ie,ee,te,D,B,K,$,se,j;class ne extends Error{}class pe extends le{constructor(e){var t,r,n,o;if(super(),_.add(this),L.set(this,void 0),M.set(this,void 0),I.set(this,0),R.set(this,void 0),N.set(this,void 0),z.set(this,0),E.set(this,void 0),O.set(this,void 0),P.set(this,void 0),k.set(this,void 0),S.set(this,0),W.set(this,void 0),C.set(this,void 0),q.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:de,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);v(this,L,e.carryoverConcurrencyCount,"f"),v(this,M,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),v(this,R,e.intervalCap,"f"),v(this,N,e.interval,"f"),v(this,P,new e.queueClass,"f"),v(this,k,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,v(this,q,e.throwOnTimeout===!0,"f"),v(this,C,e.autoStart===!1,"f")}get concurrency(){return i(this,W,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);v(this,W,e,"f"),i(this,_,"m",$).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:i(this,q,"f"),...t},new Promise((r,n)=>{i(this,P,"f").enqueue(async()=>{var o,d,h;v(this,S,(d=i(this,S,"f"),d++,d),"f"),v(this,I,(h=i(this,I,"f"),h++,h),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ne("The task was aborted.");let a=e({signal:t.signal});t.timeout&&(a=he(Promise.resolve(a),t.timeout)),t.signal&&(a=Promise.race([a,i(this,_,"m",se).call(this,t.signal)]));const u=await a;r(u),this.emit("completed",u)}catch(a){if(a instanceof re&&!t.throwOnTimeout){r();return}n(a),this.emit("error",a)}finally{i(this,_,"m",ie).call(this)}},t),this.emit("add"),i(this,_,"m",D).call(this)})}async addAll(e,t){return Promise.all(e.map(async r=>this.add(r,t)))}start(){return i(this,C,"f")?(v(this,C,!1,"f"),i(this,_,"m",$).call(this),this):this}pause(){v(this,C,!0,"f")}clear(){v(this,P,new(i(this,k,"f")),"f")}async onEmpty(){i(this,P,"f").size!==0&&await i(this,_,"m",j).call(this,"empty")}async onSizeLessThan(e){i(this,P,"f").size<e||await i(this,_,"m",j).call(this,"next",()=>i(this,P,"f").size<e)}async onIdle(){i(this,S,"f")===0&&i(this,P,"f").size===0||await i(this,_,"m",j).call(this,"idle")}get size(){return i(this,P,"f").size}sizeBy(e){return i(this,P,"f").filter(e).length}get pending(){return i(this,S,"f")}get isPaused(){return i(this,C,"f")}}L=new WeakMap,M=new WeakMap,I=new WeakMap,R=new WeakMap,N=new WeakMap,z=new WeakMap,E=new WeakMap,O=new WeakMap,P=new WeakMap,k=new WeakMap,S=new WeakMap,W=new WeakMap,C=new WeakMap,q=new WeakMap,_=new WeakSet,X=function(){return i(this,M,"f")||i(this,I,"f")<i(this,R,"f")},Z=function(){return i(this,S,"f")<i(this,W,"f")},ie=function(){var e;v(this,S,(e=i(this,S,"f"),e--,e),"f"),i(this,_,"m",D).call(this),this.emit("next")},ee=function(){i(this,_,"m",K).call(this),i(this,_,"m",B).call(this),v(this,O,void 0,"f")},te=function(){const e=Date.now();if(i(this,E,"f")===void 0){const t=i(this,z,"f")-e;if(t<0)v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f");else return i(this,O,"f")===void 0&&v(this,O,setTimeout(()=>{i(this,_,"m",ee).call(this)},t),"f"),!0}return!1},D=function(){if(i(this,P,"f").size===0)return i(this,E,"f")&&clearInterval(i(this,E,"f")),v(this,E,void 0,"f"),this.emit("empty"),i(this,S,"f")===0&&this.emit("idle"),!1;if(!i(this,C,"f")){const e=!i(this,_,"a",te);if(i(this,_,"a",X)&&i(this,_,"a",Z)){const t=i(this,P,"f").dequeue();return t?(this.emit("active"),t(),e&&i(this,_,"m",B).call(this),!0):!1}}return!1},B=function(){i(this,M,"f")||i(this,E,"f")!==void 0||(v(this,E,setInterval(()=>{i(this,_,"m",K).call(this)},i(this,N,"f")),"f"),v(this,z,Date.now()+i(this,N,"f"),"f"))},K=function(){i(this,I,"f")===0&&i(this,S,"f")===0&&i(this,E,"f")&&(clearInterval(i(this,E,"f")),v(this,E,void 0,"f")),v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f"),i(this,_,"m",$).call(this)},$=function(){for(;i(this,_,"m",D).call(this););},se=async function(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(new ne("The task was aborted."))},{once:!0})})},j=async function(e,t){return new Promise(r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)})};class me{constructor(e){this.apisStorage=e}apisStorage;data=new Map;loading=new Set;pQueue=new pe({concurrency:20});async get(e){return this.data.has(e)?this.data.get(e)??null:(await this.loadAndParse(e),this.data.get(e)??null)}async load(e,t=!1){this.data.has(e)&&!t||await this.loadAndParse(e,t)}async loadAndParse(e,t=!1){if(this.loading.has(e)){await this.pQueue.add(()=>this.get(e));return}t&&this.data.delete(e),this.loading.add(e),await this.pQueue.add(async()=>{const r=p.isWebUrl(e)?p.SourceType.WEB:p.SourceType.FS,n=r===p.SourceType.WEB?e:await this.apisStorage.getAbsolutePath(e);try{const{definition:o,fileDependencies:d}=await p.loadAndBundleDefinition(n);if(!o){this.data.set(e,null),await p.clearNotificationsForSource(e);return}const h=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...h,fileDependencies:d}),await p.clearNotificationsForSource(e)}catch(o){if(this.data.set(e,null),o instanceof Error&&(o.message.includes("Unsupported specification")||o.message.includes("File not found"))){await p.clearNotificationsForSource(e);return}console.info("Error loading api "+e,o),await p.reportParseError(e,o);return}}),this.loading.delete(e)}get size(){return this.data.size}delete(e){this.data.delete(e)}getAll(){return Array.from(this.data.values()).filter(e=>e!==null)}clear(){this.data.clear(),this.loading.clear()}}class ve extends p.RootStorage{apiLoader;constructor(e,t,r){const n=new G.TauriFileSystemAdapter(e.systemFilesDir),o=new G.TauriFileSystemAdapter(e.userFilesDir);super(n,o,e,!0,t,r),this.apiLoader=new me(this.apisStorage),this.setupWriteListeners(o)}setupWriteListeners(e){e.on("write-start",t=>{this.addWatchExcludedId(t)}),e.on("write-end",t=>{this.removeWatchExcludedId(t)})}async read(){const e=this.telemetry?.startSpan("com.redocly.storage.read",[p.createResource("storageOperation","read","storage")],void 0),t=this.telemetry?.startSpan("com.redocly.storage.loadUserState",[p.createResource("storageOperation","loadUserState","storage")],e?.parentCtx),[r,n,o]=await Promise.all([this.activeEnvironmentIdStorage.read(),this.tabsStateStorage.read(),this.environmentsStorage.read()]);t?.setAttribute("status","completed"),t?.setAttribute("environmentCount",o.length),t?.setStatus(p.SpanStatusCode.OK),t?.end();const{apiFiles:d,collectionFiles:h}=await this.detectProjectFiles(e);await this.loadAndParseApis(d,e);const u=(await this.loadAndParseCollections(h,e)).filter(l=>l!==null);this.collectionsStorage.setItemIds(u.map(l=>l.id));const f=this.apiLoader.getAll();return this.apisStorage.setItemIds(f.map(l=>l.id)),e?.setAttribute("status","completed"),e?.setStatus(p.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:n,environments:o,apis:f,collections:u}}async detectProjectFiles(e){const t=this.telemetry?.startSpan("com.redocly.storage.detectFiles",[p.createResource("storageOperation","detectFiles","storage")],e?.parentCtx),{api_files:r,collection_files:n}=await p.invoke("fs_scan",{dir:this.project.userFilesDir});return t?.setAttribute("status","completed"),t?.setAttribute("filesCount",r.length+n.length),t?.setAttribute("apiFilesCount",r.length),t?.setAttribute("collectionFilesCount",n.length),t?.setStatus(p.SpanStatusCode.OK),t?.end(),{apiFiles:r,collectionFiles:n}}readEnviroments(){return this.environmentsStorage.read()}deleteApiFromCache(e){this.apiLoader.delete(e)}async loadAndParseApis(e,t,r=!1){const n=this.telemetry?.startSpan("com.redocly.storage.parseApis",[{...p.createResource("storageOperation","parseApis","storage"),apisCount:e.length}],t?.parentCtx),o=await Y.promiseMapLimit(e,20,async d=>{try{return await this.apiLoader.load(d.relative_path,r),this.apiLoader.get(d.relative_path)}catch(h){return console.info(`Error parsing YAML/JSON file ${d.absolute_path}:`,h),await p.reportParseError(d.relative_path,h),null}});return n?.setAttribute("status","completed"),n?.setAttribute("parsedApisCount",this.apiLoader.size),n?.setStatus(p.SpanStatusCode.OK),n?.end(),o}async loadAndParseCollections(e,t){const r=this.telemetry?.startSpan("com.redocly.storage.parseCollections",[{...p.createResource("storageOperation","parseCollections","storage"),collectionsCount:e.length}],t?.parentCtx),n=await Y.promiseMapLimit(e,20,async o=>{try{const d=await this.userFilesStorage.get(o.relative_path);if(!d)return null;const h=p.yaml.load(d);if(typeof h!="object"||h===null||typeof h.arazzo!="string")return await p.clearNotificationsForSource(o.relative_path),null;const a=[];await Promise.all(h.sourceDescriptions?.map(async l=>{const g=l.type,y=l.url,m=!g||g==="openapi",b=await p.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:y,collectionId:o.relative_path});if(m){const c=await this.apiLoader.get(b);c&&a.push(c)}}));const u=await p.PathUtils.join(this.project.userFilesDir,o.relative_path),f=await this.collectionsStorage.parse({uri:o.relative_path,type:p.SourceType.FS,content:h,fileDependencies:new Set([u])},a);return await p.clearNotificationsForSource(o.relative_path),f}catch(d){return console.info(`Error parsing Arazzo file ${o.relative_path}:`,d),await p.reportParseError(o.relative_path,d),null}});return r?.setAttribute("status","completed"),r?.setAttribute("parsedCollectionsCount",n.length),r?.setStatus(p.SpanStatusCode.OK),r?.end(),n}}exports.TauriRootStorage=ve;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./replay-index-D3evrr0U.js"),Y=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-q89YsNXx.js");var U={exports:{}},V;function oe(){return V||(V=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(a,u,f){this.fn=a,this.context=u,this.once=f||!1}function o(a,u,f,l,g){if(typeof f!="function")throw new TypeError("The listener must be a function");var y=new n(f,l||a,g),m=t?t+u:u;return a._events[m]?a._events[m].fn?a._events[m]=[a._events[m],y]:a._events[m].push(y):(a._events[m]=y,a._eventsCount++),a}function d(a,u){--a._eventsCount===0?a._events=new r:delete a._events[u]}function h(){this._events=new r,this._eventsCount=0}h.prototype.eventNames=function(){var u=[],f,l;if(this._eventsCount===0)return u;for(l in f=this._events)e.call(f,l)&&u.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(f)):u},h.prototype.listeners=function(u){var f=t?t+u:u,l=this._events[f];if(!l)return[];if(l.fn)return[l.fn];for(var g=0,y=l.length,m=new Array(y);g<y;g++)m[g]=l[g].fn;return m},h.prototype.listenerCount=function(u){var f=t?t+u:u,l=this._events[f];return l?l.fn?1:l.length:0},h.prototype.emit=function(u,f,l,g,y,m){var b=t?t+u:u;if(!this._events[b])return!1;var c=this._events[b],C=arguments.length,F,w;if(c.fn){switch(c.once&&this.removeListener(u,c.fn,void 0,!0),C){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,f),!0;case 3:return c.fn.call(c.context,f,l),!0;case 4:return c.fn.call(c.context,f,l,g),!0;case 5:return c.fn.call(c.context,f,l,g,y),!0;case 6:return c.fn.call(c.context,f,l,g,y,m),!0}for(w=1,F=new Array(C-1);w<C;w++)F[w-1]=arguments[w];c.fn.apply(c.context,F)}else{var ae=c.length,x;for(w=0;w<ae;w++)switch(c[w].once&&this.removeListener(u,c[w].fn,void 0,!0),C){case 1:c[w].fn.call(c[w].context);break;case 2:c[w].fn.call(c[w].context,f);break;case 3:c[w].fn.call(c[w].context,f,l);break;case 4:c[w].fn.call(c[w].context,f,l,g);break;default:if(!F)for(x=1,F=new Array(C-1);x<C;x++)F[x-1]=arguments[x];c[w].fn.apply(c[w].context,F)}}return!0},h.prototype.on=function(u,f,l){return o(this,u,f,l,!1)},h.prototype.once=function(u,f,l){return o(this,u,f,l,!0)},h.prototype.removeListener=function(u,f,l,g){var y=t?t+u:u;if(!this._events[y])return this;if(!f)return d(this,y),this;var m=this._events[y];if(m.fn)m.fn===f&&(!g||m.once)&&(!l||m.context===l)&&d(this,y);else{for(var b=0,c=[],C=m.length;b<C;b++)(m[b].fn!==f||g&&!m[b].once||l&&m[b].context!==l)&&c.push(m[b]);c.length?this._events[y]=c.length===1?c[0]:c:d(this,y)}return this},h.prototype.removeAllListeners=function(u){var f;return u?(f=t?t+u:u,this._events[f]&&d(this,f)):(this._events=new r,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,s.exports=h})(U)),U.exports}var ue=oe();const le=p.getDefaultExportFromCjs(ue);class re extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ce=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const J=s=>globalThis.DOMException===void 0?new ce(s):new DOMException(s),H=s=>{const e=s.reason===void 0?J("This operation was aborted."):s.reason;return e instanceof Error?e:J(e)};function he(s,e,t,r){let n;const o=new Promise((d,h)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){d(s);return}if(r={customTimers:{setTimeout,clearTimeout},...r},r.signal){const{signal:a}=r;a.aborted&&h(H(a)),a.addEventListener("abort",()=>{h(H(a))})}n=r.customTimers.setTimeout.call(void 0,()=>{const a=`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(a);typeof s.cancel=="function"&&s.cancel(),h(u)},e),(async()=>{try{d(await s)}catch(a){h(a)}finally{r.customTimers.clearTimeout.call(void 0,n)}})()});return o.clear=()=>{clearTimeout(n),n=void 0},o}function fe(s,e,t){let r=0,n=s.length;for(;n>0;){const o=Math.trunc(n/2);let d=r+o;t(s[d],e)<=0?(r=++d,n-=o+1):n=o}return r}var Q=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},A;class de{constructor(){A.set(this,[])}enqueue(e,t){t={priority:0,...t};const r={priority:t.priority,run:e};if(this.size&&Q(this,A,"f")[this.size-1].priority>=t.priority){Q(this,A,"f").push(r);return}const n=fe(Q(this,A,"f"),r,(o,d)=>d.priority-o.priority);Q(this,A,"f").splice(n,0,r)}dequeue(){const e=Q(this,A,"f").shift();return e?.run}filter(e){return Q(this,A,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Q(this,A,"f").length}}A=new WeakMap;var v=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},i=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},_,L,M,I,R,N,z,E,O,P,k,S,W,T,q,X,Z,ie,ee,te,D,B,K,$,se,j;class ne extends Error{}class pe extends le{constructor(e){var t,r,n,o;if(super(),_.add(this),L.set(this,void 0),M.set(this,void 0),I.set(this,0),R.set(this,void 0),N.set(this,void 0),z.set(this,0),E.set(this,void 0),O.set(this,void 0),P.set(this,void 0),k.set(this,void 0),S.set(this,0),W.set(this,void 0),T.set(this,void 0),q.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:de,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);v(this,L,e.carryoverConcurrencyCount,"f"),v(this,M,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),v(this,R,e.intervalCap,"f"),v(this,N,e.interval,"f"),v(this,P,new e.queueClass,"f"),v(this,k,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,v(this,q,e.throwOnTimeout===!0,"f"),v(this,T,e.autoStart===!1,"f")}get concurrency(){return i(this,W,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);v(this,W,e,"f"),i(this,_,"m",$).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:i(this,q,"f"),...t},new Promise((r,n)=>{i(this,P,"f").enqueue(async()=>{var o,d,h;v(this,S,(d=i(this,S,"f"),d++,d),"f"),v(this,I,(h=i(this,I,"f"),h++,h),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ne("The task was aborted.");let a=e({signal:t.signal});t.timeout&&(a=he(Promise.resolve(a),t.timeout)),t.signal&&(a=Promise.race([a,i(this,_,"m",se).call(this,t.signal)]));const u=await a;r(u),this.emit("completed",u)}catch(a){if(a instanceof re&&!t.throwOnTimeout){r();return}n(a),this.emit("error",a)}finally{i(this,_,"m",ie).call(this)}},t),this.emit("add"),i(this,_,"m",D).call(this)})}async addAll(e,t){return Promise.all(e.map(async r=>this.add(r,t)))}start(){return i(this,T,"f")?(v(this,T,!1,"f"),i(this,_,"m",$).call(this),this):this}pause(){v(this,T,!0,"f")}clear(){v(this,P,new(i(this,k,"f")),"f")}async onEmpty(){i(this,P,"f").size!==0&&await i(this,_,"m",j).call(this,"empty")}async onSizeLessThan(e){i(this,P,"f").size<e||await i(this,_,"m",j).call(this,"next",()=>i(this,P,"f").size<e)}async onIdle(){i(this,S,"f")===0&&i(this,P,"f").size===0||await i(this,_,"m",j).call(this,"idle")}get size(){return i(this,P,"f").size}sizeBy(e){return i(this,P,"f").filter(e).length}get pending(){return i(this,S,"f")}get isPaused(){return i(this,T,"f")}}L=new WeakMap,M=new WeakMap,I=new WeakMap,R=new WeakMap,N=new WeakMap,z=new WeakMap,E=new WeakMap,O=new WeakMap,P=new WeakMap,k=new WeakMap,S=new WeakMap,W=new WeakMap,T=new WeakMap,q=new WeakMap,_=new WeakSet,X=function(){return i(this,M,"f")||i(this,I,"f")<i(this,R,"f")},Z=function(){return i(this,S,"f")<i(this,W,"f")},ie=function(){var e;v(this,S,(e=i(this,S,"f"),e--,e),"f"),i(this,_,"m",D).call(this),this.emit("next")},ee=function(){i(this,_,"m",K).call(this),i(this,_,"m",B).call(this),v(this,O,void 0,"f")},te=function(){const e=Date.now();if(i(this,E,"f")===void 0){const t=i(this,z,"f")-e;if(t<0)v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f");else return i(this,O,"f")===void 0&&v(this,O,setTimeout(()=>{i(this,_,"m",ee).call(this)},t),"f"),!0}return!1},D=function(){if(i(this,P,"f").size===0)return i(this,E,"f")&&clearInterval(i(this,E,"f")),v(this,E,void 0,"f"),this.emit("empty"),i(this,S,"f")===0&&this.emit("idle"),!1;if(!i(this,T,"f")){const e=!i(this,_,"a",te);if(i(this,_,"a",X)&&i(this,_,"a",Z)){const t=i(this,P,"f").dequeue();return t?(this.emit("active"),t(),e&&i(this,_,"m",B).call(this),!0):!1}}return!1},B=function(){i(this,M,"f")||i(this,E,"f")!==void 0||(v(this,E,setInterval(()=>{i(this,_,"m",K).call(this)},i(this,N,"f")),"f"),v(this,z,Date.now()+i(this,N,"f"),"f"))},K=function(){i(this,I,"f")===0&&i(this,S,"f")===0&&i(this,E,"f")&&(clearInterval(i(this,E,"f")),v(this,E,void 0,"f")),v(this,I,i(this,L,"f")?i(this,S,"f"):0,"f"),i(this,_,"m",$).call(this)},$=function(){for(;i(this,_,"m",D).call(this););},se=async function(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(new ne("The task was aborted."))},{once:!0})})},j=async function(e,t){return new Promise(r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)})};class me{constructor(e){this.apisStorage=e}apisStorage;data=new Map;loading=new Set;pQueue=new pe({concurrency:20});async get(e){return this.data.has(e)?this.data.get(e)??null:(await this.loadAndParse(e),this.data.get(e)??null)}async load(e,t=!1){this.data.has(e)&&!t||await this.loadAndParse(e,t)}async loadAndParse(e,t=!1){if(this.loading.has(e)){await this.pQueue.add(()=>this.get(e));return}t&&this.data.delete(e),this.loading.add(e),await this.pQueue.add(async()=>{const r=p.isWebUrl(e)?p.SourceType.WEB:p.SourceType.FS,n=r===p.SourceType.WEB?e:await this.apisStorage.getAbsolutePath(e);try{const{definition:o,fileDependencies:d}=await p.loadAndBundleDefinition(n);if(!o){this.data.set(e,null),await p.clearNotificationsForSource(e);return}const h=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...h,fileDependencies:d}),await p.clearNotificationsForSource(e)}catch(o){if(this.data.set(e,null),o instanceof Error&&(o.message.includes("Unsupported specification")||o.message.includes("File not found"))){await p.clearNotificationsForSource(e);return}console.info("Error loading api "+e,o),await p.reportParseError(e,o);return}}),this.loading.delete(e)}get size(){return this.data.size}delete(e){this.data.delete(e)}getAll(){return Array.from(this.data.values()).filter(e=>e!==null)}clear(){this.data.clear(),this.loading.clear()}}class ve extends p.RootStorage{apiLoader;constructor(e,t,r){const n=new G.TauriFileSystemAdapter(e.systemFilesDir),o=new G.TauriFileSystemAdapter(e.userFilesDir);super(n,o,e,!0,!1,t,r),this.apiLoader=new me(this.apisStorage),this.setupWriteListeners(o)}setupWriteListeners(e){e.on("write-start",t=>{this.addWatchExcludedId(t)}),e.on("write-end",t=>{this.removeWatchExcludedId(t)})}async read(){const e=this.telemetry?.startSpan("com.redocly.storage.read",[p.createResource("storageOperation","read","storage")],void 0),t=this.telemetry?.startSpan("com.redocly.storage.loadUserState",[p.createResource("storageOperation","loadUserState","storage")],e?.parentCtx),[r,n,o]=await Promise.all([this.activeEnvironmentIdStorage.read(),this.tabsStateStorage.read(),this.environmentsStorage.read()]);t?.setAttribute("status","completed"),t?.setAttribute("environmentCount",o.length),t?.setStatus(p.SpanStatusCode.OK),t?.end();const{apiFiles:d,collectionFiles:h}=await this.detectProjectFiles(e);await this.loadAndParseApis(d,e);const u=(await this.loadAndParseCollections(h,e)).filter(l=>l!==null);this.collectionsStorage.setItemIds(u.map(l=>l.id));const f=this.apiLoader.getAll();return this.apisStorage.setItemIds(f.map(l=>l.id)),e?.setAttribute("status","completed"),e?.setStatus(p.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:n,environments:o,apis:f,collections:u,configFileError:this.getEnvironmentsConfigError()}}async detectProjectFiles(e){const t=this.telemetry?.startSpan("com.redocly.storage.detectFiles",[p.createResource("storageOperation","detectFiles","storage")],e?.parentCtx),{api_files:r,collection_files:n}=await p.invoke("fs_scan",{dir:this.project.userFilesDir});return t?.setAttribute("status","completed"),t?.setAttribute("filesCount",r.length+n.length),t?.setAttribute("apiFilesCount",r.length),t?.setAttribute("collectionFilesCount",n.length),t?.setStatus(p.SpanStatusCode.OK),t?.end(),{apiFiles:r,collectionFiles:n}}readEnviroments(){return this.environmentsStorage.read()}deleteApiFromCache(e){this.apiLoader.delete(e)}async loadAndParseApis(e,t,r=!1){const n=this.telemetry?.startSpan("com.redocly.storage.parseApis",[{...p.createResource("storageOperation","parseApis","storage"),apisCount:e.length}],t?.parentCtx),o=await Y.promiseMapLimit(e,20,async d=>{try{return await this.apiLoader.load(d.relative_path,r),this.apiLoader.get(d.relative_path)}catch(h){return console.info(`Error parsing YAML/JSON file ${d.absolute_path}:`,h),await p.reportParseError(d.relative_path,h),null}});return n?.setAttribute("status","completed"),n?.setAttribute("parsedApisCount",this.apiLoader.size),n?.setStatus(p.SpanStatusCode.OK),n?.end(),o}async loadAndParseCollections(e,t){const r=this.telemetry?.startSpan("com.redocly.storage.parseCollections",[{...p.createResource("storageOperation","parseCollections","storage"),collectionsCount:e.length}],t?.parentCtx),n=await Y.promiseMapLimit(e,20,async o=>{try{const d=await this.userFilesStorage.get(o.relative_path);if(!d)return null;const h=p.yaml.load(d);if(typeof h!="object"||h===null||typeof h.arazzo!="string")return await p.clearNotificationsForSource(o.relative_path),null;const a=[];await Promise.all(h.sourceDescriptions?.map(async l=>{const g=l.type,y=l.url,m=!g||g==="openapi",b=await p.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:y,collectionId:o.relative_path});if(m){const c=await this.apiLoader.get(b);c&&a.push(c)}}));const u=await p.PathUtils.join(this.project.userFilesDir,o.relative_path),f=await this.collectionsStorage.parse({uri:o.relative_path,type:p.SourceType.FS,content:h,fileDependencies:new Set([u])},a);return await p.clearNotificationsForSource(o.relative_path),f}catch(d){return console.info(`Error parsing Arazzo file ${o.relative_path}:`,d),await p.reportParseError(o.relative_path,d),null}});return r?.setAttribute("status","completed"),r?.setAttribute("parsedCollectionsCount",n.length),r?.setStatus(p.SpanStatusCode.OK),r?.end(),n}}exports.TauriRootStorage=ve;
@@ -1,6 +1,6 @@
1
- import { g as he, a as fe, S as D, l as de, c as W, r as J, R as pe, b as F, d as O, i as me, y as ve, e as _e, P as we } from "./replay-index-B2RZCGOF.js";
1
+ import { g as he, a as fe, S as D, l as de, b as W, r as J, R as pe, d as F, e as O, i as me, y as ve, f as _e, P as we } from "./replay-index-BizzVzWT.js";
2
2
  import { p as H } from "./replay-promise-map-limit-Db_42GvV.js";
3
- import { TauriFileSystemAdapter as X } from "./replay-TauriFileSystemAdapter-BnSXgnQc.js";
3
+ import { TauriFileSystemAdapter as X } from "./replay-TauriFileSystemAdapter-CocGBrH_.js";
4
4
  var Y = { exports: {} }, Z;
5
5
  function ye() {
6
6
  return Z || (Z = 1, (function(i) {
@@ -469,6 +469,7 @@ class Oe extends pe {
469
469
  o,
470
470
  e,
471
471
  !0,
472
+ !1,
472
473
  t,
473
474
  r
474
475
  ), this.apiLoader = new Ce(this.apisStorage), this.setupWriteListeners(o);
@@ -506,7 +507,8 @@ class Oe extends pe {
506
507
  tabsState: n,
507
508
  environments: o,
508
509
  apis: f,
509
- collections: l
510
+ collections: l,
511
+ configFileError: this.getEnvironmentsConfigError()
510
512
  };
511
513
  }
512
514
  async detectProjectFiles(e) {
@@ -1,7 +1,7 @@
1
- import { a as O, p as w, T as L, i as J, c as D, s as $ } from "./replay-create-model-NrGYVueM.js";
2
- import { D as g, E as _, L as S, d as M, N as W, b as I, O as z, Q as K } from "./replay-index-B2RZCGOF.js";
3
- import { g as U } from "./replay-db-BiP6dME4.js";
4
- import { L as G, C as B } from "./replay-defaults-CzR6jw9a.js";
1
+ import { a as O, p as w, T as L, i as J, c as D, s as $ } from "./replay-create-model-Dr80k74P.js";
2
+ import { F as g, G as _, O as S, e as M, Q as W, d as I, U as z, V as K } from "./replay-index-BizzVzWT.js";
3
+ import { g as U } from "./replay-db-C8RC-t2R.js";
4
+ import { L as G, C as F } from "./replay-defaults-CzR6jw9a.js";
5
5
  function y(t) {
6
6
  const e = t.toLowerCase(), n = [
7
7
  ["google.vertex", "gcp.vertex_ai"],
@@ -41,7 +41,7 @@ function N(t) {
41
41
  function E(t) {
42
42
  return typeof t == "string" ? [{ type: "text", content: t }] : Array.isArray(t) ? t.map((e) => ({ type: "text", content: e.content })) : [{ type: "text", content: t.content }];
43
43
  }
44
- function F(t) {
44
+ function V(t) {
45
45
  var e, n, o, s, a;
46
46
  switch (t.type) {
47
47
  case "text":
@@ -126,14 +126,14 @@ function F(t) {
126
126
  function h(t) {
127
127
  return !t || t.startsWith("image/") ? "image" : t.startsWith("video/") ? "video" : t.startsWith("audio/") ? "audio" : "image";
128
128
  }
129
- function V(t) {
129
+ function B(t) {
130
130
  return t.filter((e) => e.role !== "system").map((e) => {
131
131
  if (e.role === "system")
132
132
  return {
133
133
  role: "system",
134
134
  parts: [{ type: "text", content: e.content }]
135
135
  };
136
- const n = e.content.map(F);
136
+ const n = e.content.map(V);
137
137
  return { role: e.role, parts: n };
138
138
  });
139
139
  }
@@ -733,7 +733,7 @@ var nt = class {
733
733
  "gen_ai.request.top_k": n.settings.topK,
734
734
  "gen_ai.request.top_p": n.settings.topP,
735
735
  "gen_ai.input.messages": {
736
- input: () => t.promptMessages ? JSON.stringify(V(t.promptMessages)) : void 0
736
+ input: () => t.promptMessages ? JSON.stringify(B(t.promptMessages)) : void 0
737
737
  },
738
738
  ...n.baseSupplementalAttributes
739
739
  }), r = `chat ${t.modelId}`;
@@ -1506,7 +1506,7 @@ class ct {
1506
1506
  async generateTitle(e, n) {
1507
1507
  return $({
1508
1508
  model: this.model,
1509
- system: B,
1509
+ system: F,
1510
1510
  prompt: e,
1511
1511
  temperature: 0,
1512
1512
  abortSignal: n
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./replay-create-model-DB6xE5Ap.js"),l=require("./replay-index-D85qPcEF.js"),j=require("./replay-db-BZNR8xEd.js"),T=require("./replay-defaults-DVvOnvnR.js");function S(t){const e=t.toLowerCase(),n=[["google.vertex","gcp.vertex_ai"],["google.generative-ai","gcp.gemini"],["google-vertex","gcp.vertex_ai"],["amazon-bedrock","aws.bedrock"],["azure-openai","azure.ai.openai"],["anthropic","anthropic"],["openai","openai"],["azure","azure.ai.inference"],["google","gcp.gemini"],["mistral","mistral_ai"],["cohere","cohere"],["bedrock","aws.bedrock"],["groq","groq"],["deepseek","deepseek"],["perplexity","perplexity"],["xai","x_ai"]];for(const[o,r]of n)if(e===o||e.startsWith(o+".")||e.startsWith(o+"-"))return r;return t}function A(t){var e;return(e={"ai.generateText":"invoke_agent","ai.streamText":"invoke_agent","ai.generateObject":"invoke_agent","ai.streamObject":"invoke_agent","ai.embed":"embeddings","ai.embedMany":"embeddings","ai.rerank":"rerank"}[t])!=null?e:t}function O(t){return typeof t=="string"?[{type:"text",content:t}]:Array.isArray(t)?t.map(e=>({type:"text",content:e.content})):[{type:"text",content:t.content}]}function P(t){var e,n,o,r,a;switch(t.type){case"text":return{type:"text",content:t.text};case"reasoning":return{type:"reasoning",content:t.text};case"tool-call":return{type:"tool_call",id:(e=t.toolCallId)!=null?e:null,name:t.toolName,arguments:t.input};case"tool-result":{const i=t.output;let s;return i&&(i.type==="text"||i.type==="error-text"||i.type==="json"||i.type==="error-json"?s=i.value:i.type==="execution-denied"?s={denied:!0,reason:i.reason}:s=i),{type:"tool_call_response",id:(n=t.toolCallId)!=null?n:null,response:s}}case"file":{const i=t.data,s=(()=>{if(typeof i=="object"&&i!==null&&!(i instanceof URL)&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&"type"in i)switch(i.type){case"data":return i.data;case"url":return i.url;case"text":return i.text;default:return""}return i})();let p;if(s instanceof Uint8Array)p=y.convertDataContentToBase64String(s);else if(typeof s=="string"){if(s.startsWith("http://")||s.startsWith("https://"))return{type:"uri",modality:_(t.mediaType),mime_type:(o=t.mediaType)!=null?o:null,uri:s};p=s}else{if(s instanceof URL)return{type:"uri",modality:_(t.mediaType),mime_type:(r=t.mediaType)!=null?r:null,uri:s.toString()};p=String(s)}return{type:"blob",modality:_(t.mediaType),mime_type:(a=t.mediaType)!=null?a:null,content:p}}case"tool-approval-response":return{type:"tool_approval_response",approval_id:t.approvalId,approved:t.approved,reason:t.reason};case"custom":return{type:"custom",kind:t.kind};case"reasoning-file":return{type:String(t.type)};default:return{type:String(t.type)}}}function _(t){return!t||t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"image"}function v(t){return t.filter(e=>e.role!=="system").map(e=>{if(e.role==="system")return{role:"system",parts:[{type:"text",content:e.content}]};const n=e.content.map(P);return{role:e.role,parts:n}})}function k({prompt:t,messages:e}){const n=[];if(typeof t=="string")n.push({role:"user",parts:[{type:"text",content:t}]});else if(Array.isArray(t))for(const o of t){const r=M(o);r&&n.push(r)}if(e)for(const o of e){const r=M(o);r&&n.push(r)}return n}function M(t){if(t.role!=="system"){if(t.role==="user")return typeof t.content=="string"?{role:"user",parts:[{type:"text",content:t.content}]}:{role:"user",parts:t.content.map(n=>{var o,r,a,i,s,p,c,g;switch(n.type){case"text":return{type:"text",content:n.text};case"image":{const u=n.image;return u instanceof URL?{type:"uri",modality:"image",mime_type:(o=n.mediaType)!=null?o:null,uri:u.toString()}:typeof u=="string"?u.startsWith("http://")||u.startsWith("https://")?{type:"uri",modality:"image",mime_type:(r=n.mediaType)!=null?r:null,uri:u}:{type:"blob",modality:"image",mime_type:(a=n.mediaType)!=null?a:null,content:u}:{type:"blob",modality:"image",mime_type:(i=n.mediaType)!=null?i:null,content:y.convertDataContentToBase64String(u)}}case"file":{const u=n.data,f=(()=>{if(typeof u=="object"&&u!==null&&!(u instanceof URL)&&!(u instanceof Uint8Array)&&!(u instanceof ArrayBuffer)&&"type"in u)switch(u.type){case"data":return u.data;case"url":return u.url;case"text":return u.text;default:return""}return u})();return f instanceof URL?{type:"uri",modality:_(n.mediaType),mime_type:(s=n.mediaType)!=null?s:null,uri:f.toString()}:typeof f=="string"?f.startsWith("http://")||f.startsWith("https://")?{type:"uri",modality:_(n.mediaType),mime_type:(p=n.mediaType)!=null?p:null,uri:f}:{type:"blob",modality:_(n.mediaType),mime_type:(c=n.mediaType)!=null?c:null,content:f}:{type:"blob",modality:_(n.mediaType),mime_type:(g=n.mediaType)!=null?g:null,content:y.convertDataContentToBase64String(f)}}default:return{type:String(n.type)}}})};if(t.role==="assistant")return typeof t.content=="string"?{role:"assistant",parts:[{type:"text",content:t.content}]}:{role:"assistant",parts:t.content.map(n=>{var o,r;switch(n.type){case"text":return{type:"text",content:n.text};case"reasoning":return{type:"reasoning",content:n.text};case"tool-call":return{type:"tool_call",id:(o=n.toolCallId)!=null?o:null,name:n.toolName,arguments:n.input};case"tool-result":{const a=n.output;let i;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?i=a.value:a.type==="execution-denied"?i={denied:!0,reason:a.reason}:i=a),{type:"tool_call_response",id:(r=n.toolCallId)!=null?r:null,response:i}}default:return{type:String(n.type)}}})};if(t.role==="tool")return{role:"tool",parts:t.content.map(n=>{var o;if(n.type==="tool-result"){const r=n.output;let a;return r&&(r.type==="text"||r.type==="error-text"||r.type==="json"||r.type==="error-json"?a=r.value:r.type==="execution-denied"?a={denied:!0,reason:r.reason}:a=r),{type:"tool_call_response",id:(o=n.toolCallId)!=null?o:null,response:a}}return{type:String(n.type)}})}}}function N({text:t,reasoning:e,toolCalls:n,files:o,finishReason:r}){const a=[];if(e)for(const i of e)"text"in i&&i.text&&a.push({type:"reasoning",content:i.text});if(t!=null&&t.length>0&&a.push({type:"text",content:t}),n)for(const i of n)a.push({type:"tool_call",id:i.toolCallId,name:i.toolName,arguments:i.input});if(o)for(const i of o)a.push({type:"blob",modality:_(i.mediaType),mime_type:i.mediaType,content:i.base64});return[{role:"assistant",parts:a,finish_reason:q(r)}]}function E({objectText:t,finishReason:e}){return[{role:"assistant",parts:[{type:"text",content:t}],finish_reason:q(e)}]}function q(t){var e;return(e={stop:"stop",length:"length","content-filter":"content_filter","tool-calls":"tool_call",error:"error",other:"stop",unknown:"stop"}[t])!=null?e:t}function h(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:l.SpanStatusCode.ERROR,message:e.message})):t.setStatus({code:l.SpanStatusCode.ERROR})}function w(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function I(t){if(!Array.isArray(t))return t;const e=new Set(t.filter(w).map(o=>typeof o));if(e.size!==1)return;const[n]=e;return n==="string"?t.filter(o=>typeof o=="string"):n==="number"?t.filter(o=>typeof o=="number"):t.filter(o=>typeof o=="boolean")}function L(t){const e={};for(const[n,o]of Object.entries(t??{})){if(o==null)continue;const r=I(o);r!=null&&(e[n]=r)}return e}function J(t){return t?.isEnabled!==!1}function d(t,e){if(!J(t))return{};const n={};for(const[o,r]of Object.entries(e)){if(r==null)continue;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(t?.recordInputs===!1)continue;const i=r.input();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(t?.recordOutputs===!1)continue;const i=r.output();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}const a=I(r);a!=null&&(n[o]=a)}return n}var D={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function K(t){var e,n,o,r,a,i,s,p;return{...D,usage:(e=t.usage)!=null?e:!1,providerMetadata:(n=t.providerMetadata)!=null?n:!1,embedding:(o=t.embedding)!=null?o:!1,reranking:(r=t.reranking)!=null?r:!1,runtimeContext:(a=t.runtimeContext)!=null?a:!1,headers:(i=t.headers)!=null?i:!1,toolChoice:(s=t.toolChoice)!=null?s:!1,schema:(p=t.schema)!=null?p:!1}}function $(t){const e={};for(const[n,o]of Object.entries(t??{}))R(e,`ai.settings.context.${n}`,o);return e}function R(t,e,n){if(n!=null){if(Array.isArray(n)||typeof n!="object"){t[e]=n;return}for(const[o,r]of Object.entries(n))R(t,`${e}.${o}`,r)}}function x(t){return Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!=null).map(([e,n])=>[`ai.request.headers.${e}`,n]))}function b(t){var e,n,o;return{"ai.usage.inputTokenDetails.noCacheTokens":(e=t.inputTokenDetails)==null?void 0:e.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":(n=t.outputTokenDetails)==null?void 0:n.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(o=t.outputTokenDetails)==null?void 0:o.reasoningTokens}}function m(t,e,n){const o={};for(const[r,a]of Object.entries(n))!e[r]||a==null||Object.assign(o,d(t,a));return o}function C(t){return t==null?void 0:t/1e3}function W(t){var e;return{"gen_ai.client.operation.duration":C(t.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":C(t.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":C((e=t.timeBetweenOutputChunksMs)==null?void 0:e.avg)}}var z=class{constructor(t={}){this.callStates=new Map;var e;this.tracer=(e=t.tracer)!=null?e:l.trace.getTracer("gen_ai"),this.supplementalAttributes=K(t),this.enrichSpan=t.enrichSpan}getCallState(t){return this.callStates.get(t)}cleanupCallState(t){this.callStates.delete(t)}getSpanAttributes({attributes:t,spanType:e,operationId:n,callId:o,runtimeContext:r}){var a;let i;try{i=(a=this.enrichSpan)==null?void 0:a.call(this,{spanType:e,operationId:n,callId:o,runtimeContext:r})}catch{i=void 0}return{...L(i),...t}}executeTool({callId:t,toolCallId:e,execute:n}){var o;const r=(o=this.getCallState(t))==null?void 0:o.toolSpans.get(e);return r==null?n():l.context.with(r.context,n)}executeLanguageModelCall({callId:t,execute:e}){var n;const o=this.getCallState(t),r=(n=o?.inferenceContext)!=null?n:o?.stepContext;return r==null?e():l.context.with(r,e)}onStart(t){if(t.operationId==="ai.embed"||t.operationId==="ai.embedMany"){this.onEmbedOperationStart(t);return}if(t.operationId==="ai.rerank"){this.onRerankOperationStart(t);return}if(t.operationId==="ai.generateObject"||t.operationId==="ai.streamObject"){this.onObjectOperationStart(t);return}this.onGenerateStart(t)}onGenerateStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,stopSequences:t.stopSequences,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=t.runtimeContext,s=m(n,this.supplementalAttributes,{runtimeContext:$(i),headers:x(t.headers)}),p=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.stop_sequences":t.stopSequences,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.instructions?{input:()=>JSON.stringify(O(t.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:void 0,messages:t.messages}))},...s}),c=`${a} ${t.modelId}`,g=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:p,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:i}),kind:l.SpanKind.INTERNAL}),u=l.trace.setSpan(l.context.active(),g);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:g,rootContext:u,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:i,baseSupplementalAttributes:s})}onObjectOperationStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=m(n,this.supplementalAttributes,{headers:x(t.headers)}),s=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.system?{input:()=>JSON.stringify(O(t.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:t.prompt,messages:t.messages}))},...i,...m(n,this.supplementalAttributes,{schema:{"ai.schema":t.schema?{input:()=>JSON.stringify(t.schema)}:void 0,"ai.schema.name":t.schemaName,"ai.schema.description":t.schemaDescription,"ai.settings.output":t.output}})}),p=`${a} ${t.modelId}`,c=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.INTERNAL}),g=l.trace.setSpan(l.context.active(),c);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:c,rootContext:g,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:i})}onObjectStepStart(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan||!n.rootContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>t.promptMessages?JSON.stringify(v(t.promptMessages)):void 0},...n.baseSupplementalAttributes}),i=`chat ${t.modelId}`;n.inferenceSpan=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.rootContext),n.inferenceContext=l.trace.setSpan(n.rootContext,n.inferenceSpan)}onObjectStepEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.inferenceSpan)return;const{telemetry:o}=n;n.inferenceSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.response.id,"gen_ai.response.model":t.response.modelId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(E({objectText:t.objectText,finishReason:t.finishReason}))}catch{return t.objectText}}},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0}onEmbedOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=t.value,a=t.operationId==="ai.embedMany",i=d(e,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>r.map(g=>JSON.stringify(g))}}:{"ai.value":{input:()=>JSON.stringify(r)}}})}),s=`embeddings ${t.modelId}`,p=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),c=l.trace.setSpan(l.context.active(),p);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:p,rootContext:c,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onStepStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e;e.runtimeContext=t.runtimeContext;const o=d(n,{"gen_ai.operation.name":"agent_step",...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>t.stepToolChoice!=null?JSON.stringify(t.stepToolChoice):void 0}}})});e.stepSpan=this.tracer.startSpan(`step ${t.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:o,spanType:"step",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.rootContext),e.stepContext=l.trace.setSpan(e.rootContext,e.stepSpan)}onLanguageModelCallStart(t){var e;const n=this.getCallState(t.callId);if(!n?.stepContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.stop_sequences":n.settings.stopSequences,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>{const i=k({prompt:void 0,messages:t.messages});return i.length>0?JSON.stringify(i):void 0}},"gen_ai.tool.definitions":{input:()=>t.tools?JSON.stringify(t.tools):void 0}});n.inferenceSpan=this.tracer.startSpan(`chat ${t.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.stepContext),n.inferenceContext=l.trace.setSpan(n.stepContext,n.inferenceSpan)}onLanguageModelCallEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.inferenceSpan)return;const{telemetry:r}=o;o.inferenceSpan.setAttributes(d(r,{...W(t.performance),"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.responseId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(N({text:t.content.filter(a=>a.type==="text").map(a=>a.text).join("")||void 0,reasoning:t.content.filter(a=>a.type==="reasoning"),toolCalls:t.content.filter(a=>a.type==="tool-call"),files:t.content.filter(a=>a.type==="file").map(a=>a.file),finishReason:t.finishReason}))},...m(r,this.supplementalAttributes,{usage:b(t.usage)})})),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0}onToolExecutionStart(t){const e=this.getCallState(t.callId);if(!e?.stepContext)return;const{telemetry:n}=e,{toolCall:o}=t,r=d(n,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":o.toolName,"gen_ai.tool.call.id":o.toolCallId,"gen_ai.tool.type":"function","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(o.input)}}),a=`execute_tool ${o.toolName}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"tool",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.stepContext),s=l.trace.setSpan(e.stepContext,i);e.toolSpans.set(o.toolCallId,{span:i,context:s})}onToolExecutionEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.toolSpans.get(t.toolCall.toolCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e,{toolOutput:a}=t;if(o.setAttributes(d(r,{"gen_ai.execute_tool.duration":C(t.toolExecutionMs)})),a.type==="tool-result")try{o.setAttributes(d(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else h(o,a.error);o.end(),e.toolSpans.delete(t.toolCall.toolCallId)}onStepEnd(t){const e=this.getCallState(t.callId);if(!e?.stepSpan)return;const{telemetry:n}=e;e.stepSpan.setAttributes(m(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})),e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0}onStepFinish(t){this.onStepEnd(t)}onEnd(t){const e=this.getCallState(t.callId);if(e?.rootSpan){if(e.operationId==="ai.embed"||e.operationId==="ai.embedMany"){this.onEmbedOperationEnd(t);return}if(e.operationId==="ai.rerank"){this.onRerankOperationEnd(t);return}if(e.operationId==="ai.generateObject"||e.operationId==="ai.streamObject"){this.onObjectOperationEnd(t);return}this.onGenerateEnd(t)}}onGenerateEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.rootSpan)return;const{telemetry:r}=o;o.rootSpan.setAttributes(d(r,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>{var a;return JSON.stringify(N({text:(a=t.text)!=null?a:void 0,reasoning:t.finalStep.reasoning,toolCalls:t.toolCalls,files:t.files,finishReason:t.finishReason}))}},...m(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.finalStep.providerMetadata?JSON.stringify(t.finalStep.providerMetadata):void 0},usage:b(t.usage)})})),o.rootSpan.end(),this.cleanupCallState(t.callId)}onObjectOperationEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan)return;const{telemetry:o}=n;n.rootSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>t.object!=null?JSON.stringify(E({objectText:JSON.stringify(t.object),finishReason:t.finishReason})):void 0},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedOperationEnd(t){const e=this.getCallState(t.callId);if(!e?.rootSpan)return;const{telemetry:n}=e,o=e.operationId==="ai.embedMany";e.rootSpan.setAttributes(d(n,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(n,this.supplementalAttributes,{embedding:o?{"ai.embeddings":{output:()=>t.embedding.map(r=>JSON.stringify(r))}}:{"ai.embedding":{output:()=>JSON.stringify(t.embedding)}}})})),e.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>t.values.map(p=>JSON.stringify(p))}}})}),a=`embeddings ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.embedSpans.set(t.embedCallId,{span:i,context:s})}onEmbedEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.embedSpans.get(t.embedCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e;o.setAttributes(d(r,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(r,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>t.embeddings.map(a=>JSON.stringify(a))}}})})),o.end(),e.embedSpans.delete(t.embedCallId)}onRerankOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=d(e,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${t.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),s=l.trace.setSpan(l.context.active(),i);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:i,rootContext:s,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onRerankOperationEnd(t){const e=this.getCallState(t.callId);e?.rootSpan&&(e.rootSpan.end(),this.cleanupCallState(t.callId))}onRerankStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.rerankSpan={span:i,context:s}}onRerankEnd(t){const e=this.getCallState(t.callId);if(!e?.rerankSpan)return;const{span:n}=e.rerankSpan,{telemetry:o}=e;n.setAttributes(m(o,this.supplementalAttributes,{reranking:{"ai.ranking.type":t.documentsType,"ai.ranking":{output:()=>t.ranking.map(r=>JSON.stringify(r))}}})),n.end(),e.rerankSpan=void 0}onAbort(t){const e=this.getCallState(t.callId);if(e?.rootSpan){for(const{span:n}of e.toolSpans.values())n.end();e.toolSpans.clear(),e.inferenceSpan&&(e.inferenceSpan.end(),e.inferenceSpan=void 0,e.inferenceContext=void 0),e.stepSpan&&(e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0);for(const{span:n}of e.embedSpans.values())n.end();e.embedSpans.clear(),e.rerankSpan&&(e.rerankSpan.span.end(),e.rerankSpan=void 0),e.rootSpan.end(),this.cleanupCallState(t.callId)}}onError(t){var e;const n=t;if(!n?.callId)return;const o=this.getCallState(n.callId);if(!o?.rootSpan)return;const r=(e=n.error)!=null?e:t;for(const{span:a}of o.toolSpans.values())h(a,r),a.end();o.toolSpans.clear(),o.inferenceSpan&&(h(o.inferenceSpan,r),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0),o.stepSpan&&(h(o.stepSpan,r),o.stepSpan.end(),o.stepSpan=void 0,o.stepContext=void 0);for(const{span:a}of o.embedSpans.values())h(a,r),a.end();o.embedSpans.clear(),o.rerankSpan&&(h(o.rerankSpan.span,r),o.rerankSpan.span.end(),o.rerankSpan=void 0),h(o.rootSpan,r),o.rootSpan.end(),this.cleanupCallState(n.callId)}};function U(t){return y.pruneMessages({messages:t,emptyMessages:"remove",reasoning:"none",toolCalls:`before-last-${l.TOOL_CALL_MESSAGES_TO_KEEP}-messages`})}function B(t){return typeof t=="object"&&t!==null&&"role"in t&&"content"in t}function G(t){return Array.isArray(t)&&t.every(B)}function F(t,{conversationId:e,getModel:n}){let o=0;const r=()=>{const a=n?.();return a?{model_provider:a.provider,model_id:a.modelId}:{}};return{onStepStart:()=>{o+=1},onToolExecutionStart:a=>{t("com.redocly.aiChat.toolCallStarted",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,...r()}])},onToolExecutionEnd:a=>{const i=a.toolOutput.type==="tool-error";t("com.redocly.aiChat.toolCallFinished",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,success:!i,duration_ms:a.toolExecutionMs,...r(),...i&&{error:a.toolOutput.error instanceof Error?a.toolOutput.error.message:String(a.toolOutput.error)}}])},onStart:a=>{o=0,t("com.redocly.aiChat.conversationStarted",[{...l.createResource("conversation",e,"ai"),model_provider:"provider"in a?a.provider:"unknown",model_id:"modelId"in a?a.modelId:"unknown"}])},onEnd:a=>{if(!("steps"in a))return;const i=a.usage;t("com.redocly.aiChat.conversationFinished",[{...l.createResource("conversation",e,"ai"),model_provider:a.model.provider,model_id:a.model.modelId,success:!0,step_count:a.steps.length,finish_reason:a.finishReason,input_tokens:i.inputTokens,output_tokens:i.outputTokens,total_tokens:i.totalTokens}])}}}function V(t,e){const n=()=>l.trace.getSpan(l.context.active())?l.context.active():e;return{startSpan:(o,r,a)=>t.startSpan(o,r,a??e),startActiveSpan:((o,r,a,i)=>{if(typeof r=="function")return t.startActiveSpan(o,{},n(),r);if(typeof a=="function")return t.startActiveSpan(o,r,n(),a);if(i)return t.startActiveSpan(o,r,a,i);throw new Error("withParentContext: invalid startActiveSpan invocation")})}}class H{model;tools;toolLoopAgent;maxSteps;context=[];systemInstructions=j.getSystemInstructions();getActiveStateMessage;constructor(e){const{activeConversationId:n,onFinish:o,onStepFinish:r,tools:a}=e;this.maxSteps=e.maxSteps??l.DEFAULT_MAX_STEPS,this.getActiveStateMessage=e.getActiveStateMessage,this.model=this.createModel(e.model);const i=({stepNumber:c,messages:g})=>{const u=[],f=this.buildActiveStateMessage();return f&&u.push({role:"user",content:f}),c===this.maxSteps-1&&u.push({role:"user",content:T.LAST_STEP_PROMPT}),u.length===0?void 0:{messages:[...g,...u]}},s=c=>{const g=c.messages?this.prepareMessages(c.messages):void 0,u=c.prompt?this.preparePrompt(c.prompt):void 0;return{...c,model:this.model,messages:g,prompt:u,instructions:[...this.systemInstructions,...this.context],tools:this.tools??c.tools}},p=new z({...e.parentCtx&&{tracer:V(l.trace.getTracer("ai"),e.parentCtx)}});this.toolLoopAgent=new y.ToolLoopAgent({model:this.model,tools:a,stopWhen:y.isStepCount(this.maxSteps),onStepFinish:r,onFinish:o,maxOutputTokens:e.maxOutputTokens,maxRetries:e.maxRetries??l.DEFAULT_MAX_RETRIES,prepareStep:i,prepareCall:s,telemetry:{isEnabled:!0,recordInputs:!0,recordOutputs:!0,functionId:"replay-ai-chat",integrations:[p,F(e.sendEvent,{conversationId:n,getModel:()=>({provider:this.model.provider,modelId:this.model.modelId})})]}})}createModel(e){return y.createModel(e)}setModel(e){this.model=this.createModel(e)}getAgent(){return this.toolLoopAgent}addContext(e){this.context.push(...e)}registerTools(e){this.tools=e}async generateTitle(e,n){return y.streamText({model:this.model,system:T.CONVERSATION_TITLE_PROMPT,prompt:e,temperature:0,abortSignal:n}).text}buildActiveStateMessage(){if(!this.getActiveStateMessage)return null;try{return this.getActiveStateMessage()||null}catch(e){return console.error(e),null}}prepareMessages(e){return U(e)}preparePrompt(e){return G(e)?this.prepareMessages(e):e}}exports.AgentLoop=H;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./replay-create-model-CqA612v0.js"),l=require("./replay-index-D3evrr0U.js"),j=require("./replay-db-Bq7IGfIa.js"),T=require("./replay-defaults-DVvOnvnR.js");function S(t){const e=t.toLowerCase(),n=[["google.vertex","gcp.vertex_ai"],["google.generative-ai","gcp.gemini"],["google-vertex","gcp.vertex_ai"],["amazon-bedrock","aws.bedrock"],["azure-openai","azure.ai.openai"],["anthropic","anthropic"],["openai","openai"],["azure","azure.ai.inference"],["google","gcp.gemini"],["mistral","mistral_ai"],["cohere","cohere"],["bedrock","aws.bedrock"],["groq","groq"],["deepseek","deepseek"],["perplexity","perplexity"],["xai","x_ai"]];for(const[o,r]of n)if(e===o||e.startsWith(o+".")||e.startsWith(o+"-"))return r;return t}function A(t){var e;return(e={"ai.generateText":"invoke_agent","ai.streamText":"invoke_agent","ai.generateObject":"invoke_agent","ai.streamObject":"invoke_agent","ai.embed":"embeddings","ai.embedMany":"embeddings","ai.rerank":"rerank"}[t])!=null?e:t}function O(t){return typeof t=="string"?[{type:"text",content:t}]:Array.isArray(t)?t.map(e=>({type:"text",content:e.content})):[{type:"text",content:t.content}]}function P(t){var e,n,o,r,a;switch(t.type){case"text":return{type:"text",content:t.text};case"reasoning":return{type:"reasoning",content:t.text};case"tool-call":return{type:"tool_call",id:(e=t.toolCallId)!=null?e:null,name:t.toolName,arguments:t.input};case"tool-result":{const i=t.output;let s;return i&&(i.type==="text"||i.type==="error-text"||i.type==="json"||i.type==="error-json"?s=i.value:i.type==="execution-denied"?s={denied:!0,reason:i.reason}:s=i),{type:"tool_call_response",id:(n=t.toolCallId)!=null?n:null,response:s}}case"file":{const i=t.data,s=(()=>{if(typeof i=="object"&&i!==null&&!(i instanceof URL)&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&"type"in i)switch(i.type){case"data":return i.data;case"url":return i.url;case"text":return i.text;default:return""}return i})();let p;if(s instanceof Uint8Array)p=y.convertDataContentToBase64String(s);else if(typeof s=="string"){if(s.startsWith("http://")||s.startsWith("https://"))return{type:"uri",modality:_(t.mediaType),mime_type:(o=t.mediaType)!=null?o:null,uri:s};p=s}else{if(s instanceof URL)return{type:"uri",modality:_(t.mediaType),mime_type:(r=t.mediaType)!=null?r:null,uri:s.toString()};p=String(s)}return{type:"blob",modality:_(t.mediaType),mime_type:(a=t.mediaType)!=null?a:null,content:p}}case"tool-approval-response":return{type:"tool_approval_response",approval_id:t.approvalId,approved:t.approved,reason:t.reason};case"custom":return{type:"custom",kind:t.kind};case"reasoning-file":return{type:String(t.type)};default:return{type:String(t.type)}}}function _(t){return!t||t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"image"}function v(t){return t.filter(e=>e.role!=="system").map(e=>{if(e.role==="system")return{role:"system",parts:[{type:"text",content:e.content}]};const n=e.content.map(P);return{role:e.role,parts:n}})}function k({prompt:t,messages:e}){const n=[];if(typeof t=="string")n.push({role:"user",parts:[{type:"text",content:t}]});else if(Array.isArray(t))for(const o of t){const r=M(o);r&&n.push(r)}if(e)for(const o of e){const r=M(o);r&&n.push(r)}return n}function M(t){if(t.role!=="system"){if(t.role==="user")return typeof t.content=="string"?{role:"user",parts:[{type:"text",content:t.content}]}:{role:"user",parts:t.content.map(n=>{var o,r,a,i,s,p,c,g;switch(n.type){case"text":return{type:"text",content:n.text};case"image":{const u=n.image;return u instanceof URL?{type:"uri",modality:"image",mime_type:(o=n.mediaType)!=null?o:null,uri:u.toString()}:typeof u=="string"?u.startsWith("http://")||u.startsWith("https://")?{type:"uri",modality:"image",mime_type:(r=n.mediaType)!=null?r:null,uri:u}:{type:"blob",modality:"image",mime_type:(a=n.mediaType)!=null?a:null,content:u}:{type:"blob",modality:"image",mime_type:(i=n.mediaType)!=null?i:null,content:y.convertDataContentToBase64String(u)}}case"file":{const u=n.data,f=(()=>{if(typeof u=="object"&&u!==null&&!(u instanceof URL)&&!(u instanceof Uint8Array)&&!(u instanceof ArrayBuffer)&&"type"in u)switch(u.type){case"data":return u.data;case"url":return u.url;case"text":return u.text;default:return""}return u})();return f instanceof URL?{type:"uri",modality:_(n.mediaType),mime_type:(s=n.mediaType)!=null?s:null,uri:f.toString()}:typeof f=="string"?f.startsWith("http://")||f.startsWith("https://")?{type:"uri",modality:_(n.mediaType),mime_type:(p=n.mediaType)!=null?p:null,uri:f}:{type:"blob",modality:_(n.mediaType),mime_type:(c=n.mediaType)!=null?c:null,content:f}:{type:"blob",modality:_(n.mediaType),mime_type:(g=n.mediaType)!=null?g:null,content:y.convertDataContentToBase64String(f)}}default:return{type:String(n.type)}}})};if(t.role==="assistant")return typeof t.content=="string"?{role:"assistant",parts:[{type:"text",content:t.content}]}:{role:"assistant",parts:t.content.map(n=>{var o,r;switch(n.type){case"text":return{type:"text",content:n.text};case"reasoning":return{type:"reasoning",content:n.text};case"tool-call":return{type:"tool_call",id:(o=n.toolCallId)!=null?o:null,name:n.toolName,arguments:n.input};case"tool-result":{const a=n.output;let i;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?i=a.value:a.type==="execution-denied"?i={denied:!0,reason:a.reason}:i=a),{type:"tool_call_response",id:(r=n.toolCallId)!=null?r:null,response:i}}default:return{type:String(n.type)}}})};if(t.role==="tool")return{role:"tool",parts:t.content.map(n=>{var o;if(n.type==="tool-result"){const r=n.output;let a;return r&&(r.type==="text"||r.type==="error-text"||r.type==="json"||r.type==="error-json"?a=r.value:r.type==="execution-denied"?a={denied:!0,reason:r.reason}:a=r),{type:"tool_call_response",id:(o=n.toolCallId)!=null?o:null,response:a}}return{type:String(n.type)}})}}}function N({text:t,reasoning:e,toolCalls:n,files:o,finishReason:r}){const a=[];if(e)for(const i of e)"text"in i&&i.text&&a.push({type:"reasoning",content:i.text});if(t!=null&&t.length>0&&a.push({type:"text",content:t}),n)for(const i of n)a.push({type:"tool_call",id:i.toolCallId,name:i.toolName,arguments:i.input});if(o)for(const i of o)a.push({type:"blob",modality:_(i.mediaType),mime_type:i.mediaType,content:i.base64});return[{role:"assistant",parts:a,finish_reason:q(r)}]}function E({objectText:t,finishReason:e}){return[{role:"assistant",parts:[{type:"text",content:t}],finish_reason:q(e)}]}function q(t){var e;return(e={stop:"stop",length:"length","content-filter":"content_filter","tool-calls":"tool_call",error:"error",other:"stop",unknown:"stop"}[t])!=null?e:t}function h(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:l.SpanStatusCode.ERROR,message:e.message})):t.setStatus({code:l.SpanStatusCode.ERROR})}function w(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function I(t){if(!Array.isArray(t))return t;const e=new Set(t.filter(w).map(o=>typeof o));if(e.size!==1)return;const[n]=e;return n==="string"?t.filter(o=>typeof o=="string"):n==="number"?t.filter(o=>typeof o=="number"):t.filter(o=>typeof o=="boolean")}function L(t){const e={};for(const[n,o]of Object.entries(t??{})){if(o==null)continue;const r=I(o);r!=null&&(e[n]=r)}return e}function J(t){return t?.isEnabled!==!1}function d(t,e){if(!J(t))return{};const n={};for(const[o,r]of Object.entries(e)){if(r==null)continue;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(t?.recordInputs===!1)continue;const i=r.input();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(t?.recordOutputs===!1)continue;const i=r.output();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}const a=I(r);a!=null&&(n[o]=a)}return n}var D={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function K(t){var e,n,o,r,a,i,s,p;return{...D,usage:(e=t.usage)!=null?e:!1,providerMetadata:(n=t.providerMetadata)!=null?n:!1,embedding:(o=t.embedding)!=null?o:!1,reranking:(r=t.reranking)!=null?r:!1,runtimeContext:(a=t.runtimeContext)!=null?a:!1,headers:(i=t.headers)!=null?i:!1,toolChoice:(s=t.toolChoice)!=null?s:!1,schema:(p=t.schema)!=null?p:!1}}function $(t){const e={};for(const[n,o]of Object.entries(t??{}))R(e,`ai.settings.context.${n}`,o);return e}function R(t,e,n){if(n!=null){if(Array.isArray(n)||typeof n!="object"){t[e]=n;return}for(const[o,r]of Object.entries(n))R(t,`${e}.${o}`,r)}}function x(t){return Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!=null).map(([e,n])=>[`ai.request.headers.${e}`,n]))}function b(t){var e,n,o;return{"ai.usage.inputTokenDetails.noCacheTokens":(e=t.inputTokenDetails)==null?void 0:e.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":(n=t.outputTokenDetails)==null?void 0:n.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(o=t.outputTokenDetails)==null?void 0:o.reasoningTokens}}function m(t,e,n){const o={};for(const[r,a]of Object.entries(n))!e[r]||a==null||Object.assign(o,d(t,a));return o}function C(t){return t==null?void 0:t/1e3}function W(t){var e;return{"gen_ai.client.operation.duration":C(t.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":C(t.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":C((e=t.timeBetweenOutputChunksMs)==null?void 0:e.avg)}}var z=class{constructor(t={}){this.callStates=new Map;var e;this.tracer=(e=t.tracer)!=null?e:l.trace.getTracer("gen_ai"),this.supplementalAttributes=K(t),this.enrichSpan=t.enrichSpan}getCallState(t){return this.callStates.get(t)}cleanupCallState(t){this.callStates.delete(t)}getSpanAttributes({attributes:t,spanType:e,operationId:n,callId:o,runtimeContext:r}){var a;let i;try{i=(a=this.enrichSpan)==null?void 0:a.call(this,{spanType:e,operationId:n,callId:o,runtimeContext:r})}catch{i=void 0}return{...L(i),...t}}executeTool({callId:t,toolCallId:e,execute:n}){var o;const r=(o=this.getCallState(t))==null?void 0:o.toolSpans.get(e);return r==null?n():l.context.with(r.context,n)}executeLanguageModelCall({callId:t,execute:e}){var n;const o=this.getCallState(t),r=(n=o?.inferenceContext)!=null?n:o?.stepContext;return r==null?e():l.context.with(r,e)}onStart(t){if(t.operationId==="ai.embed"||t.operationId==="ai.embedMany"){this.onEmbedOperationStart(t);return}if(t.operationId==="ai.rerank"){this.onRerankOperationStart(t);return}if(t.operationId==="ai.generateObject"||t.operationId==="ai.streamObject"){this.onObjectOperationStart(t);return}this.onGenerateStart(t)}onGenerateStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,stopSequences:t.stopSequences,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=t.runtimeContext,s=m(n,this.supplementalAttributes,{runtimeContext:$(i),headers:x(t.headers)}),p=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.stop_sequences":t.stopSequences,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.instructions?{input:()=>JSON.stringify(O(t.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:void 0,messages:t.messages}))},...s}),c=`${a} ${t.modelId}`,g=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:p,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:i}),kind:l.SpanKind.INTERNAL}),u=l.trace.setSpan(l.context.active(),g);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:g,rootContext:u,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:i,baseSupplementalAttributes:s})}onObjectOperationStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=m(n,this.supplementalAttributes,{headers:x(t.headers)}),s=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.system?{input:()=>JSON.stringify(O(t.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:t.prompt,messages:t.messages}))},...i,...m(n,this.supplementalAttributes,{schema:{"ai.schema":t.schema?{input:()=>JSON.stringify(t.schema)}:void 0,"ai.schema.name":t.schemaName,"ai.schema.description":t.schemaDescription,"ai.settings.output":t.output}})}),p=`${a} ${t.modelId}`,c=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.INTERNAL}),g=l.trace.setSpan(l.context.active(),c);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:c,rootContext:g,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:i})}onObjectStepStart(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan||!n.rootContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>t.promptMessages?JSON.stringify(v(t.promptMessages)):void 0},...n.baseSupplementalAttributes}),i=`chat ${t.modelId}`;n.inferenceSpan=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.rootContext),n.inferenceContext=l.trace.setSpan(n.rootContext,n.inferenceSpan)}onObjectStepEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.inferenceSpan)return;const{telemetry:o}=n;n.inferenceSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.response.id,"gen_ai.response.model":t.response.modelId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(E({objectText:t.objectText,finishReason:t.finishReason}))}catch{return t.objectText}}},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0}onEmbedOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=t.value,a=t.operationId==="ai.embedMany",i=d(e,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>r.map(g=>JSON.stringify(g))}}:{"ai.value":{input:()=>JSON.stringify(r)}}})}),s=`embeddings ${t.modelId}`,p=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),c=l.trace.setSpan(l.context.active(),p);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:p,rootContext:c,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onStepStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e;e.runtimeContext=t.runtimeContext;const o=d(n,{"gen_ai.operation.name":"agent_step",...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>t.stepToolChoice!=null?JSON.stringify(t.stepToolChoice):void 0}}})});e.stepSpan=this.tracer.startSpan(`step ${t.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:o,spanType:"step",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.rootContext),e.stepContext=l.trace.setSpan(e.rootContext,e.stepSpan)}onLanguageModelCallStart(t){var e;const n=this.getCallState(t.callId);if(!n?.stepContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.stop_sequences":n.settings.stopSequences,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>{const i=k({prompt:void 0,messages:t.messages});return i.length>0?JSON.stringify(i):void 0}},"gen_ai.tool.definitions":{input:()=>t.tools?JSON.stringify(t.tools):void 0}});n.inferenceSpan=this.tracer.startSpan(`chat ${t.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.stepContext),n.inferenceContext=l.trace.setSpan(n.stepContext,n.inferenceSpan)}onLanguageModelCallEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.inferenceSpan)return;const{telemetry:r}=o;o.inferenceSpan.setAttributes(d(r,{...W(t.performance),"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.responseId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(N({text:t.content.filter(a=>a.type==="text").map(a=>a.text).join("")||void 0,reasoning:t.content.filter(a=>a.type==="reasoning"),toolCalls:t.content.filter(a=>a.type==="tool-call"),files:t.content.filter(a=>a.type==="file").map(a=>a.file),finishReason:t.finishReason}))},...m(r,this.supplementalAttributes,{usage:b(t.usage)})})),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0}onToolExecutionStart(t){const e=this.getCallState(t.callId);if(!e?.stepContext)return;const{telemetry:n}=e,{toolCall:o}=t,r=d(n,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":o.toolName,"gen_ai.tool.call.id":o.toolCallId,"gen_ai.tool.type":"function","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(o.input)}}),a=`execute_tool ${o.toolName}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"tool",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.stepContext),s=l.trace.setSpan(e.stepContext,i);e.toolSpans.set(o.toolCallId,{span:i,context:s})}onToolExecutionEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.toolSpans.get(t.toolCall.toolCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e,{toolOutput:a}=t;if(o.setAttributes(d(r,{"gen_ai.execute_tool.duration":C(t.toolExecutionMs)})),a.type==="tool-result")try{o.setAttributes(d(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else h(o,a.error);o.end(),e.toolSpans.delete(t.toolCall.toolCallId)}onStepEnd(t){const e=this.getCallState(t.callId);if(!e?.stepSpan)return;const{telemetry:n}=e;e.stepSpan.setAttributes(m(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})),e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0}onStepFinish(t){this.onStepEnd(t)}onEnd(t){const e=this.getCallState(t.callId);if(e?.rootSpan){if(e.operationId==="ai.embed"||e.operationId==="ai.embedMany"){this.onEmbedOperationEnd(t);return}if(e.operationId==="ai.rerank"){this.onRerankOperationEnd(t);return}if(e.operationId==="ai.generateObject"||e.operationId==="ai.streamObject"){this.onObjectOperationEnd(t);return}this.onGenerateEnd(t)}}onGenerateEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.rootSpan)return;const{telemetry:r}=o;o.rootSpan.setAttributes(d(r,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>{var a;return JSON.stringify(N({text:(a=t.text)!=null?a:void 0,reasoning:t.finalStep.reasoning,toolCalls:t.toolCalls,files:t.files,finishReason:t.finishReason}))}},...m(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.finalStep.providerMetadata?JSON.stringify(t.finalStep.providerMetadata):void 0},usage:b(t.usage)})})),o.rootSpan.end(),this.cleanupCallState(t.callId)}onObjectOperationEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan)return;const{telemetry:o}=n;n.rootSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>t.object!=null?JSON.stringify(E({objectText:JSON.stringify(t.object),finishReason:t.finishReason})):void 0},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedOperationEnd(t){const e=this.getCallState(t.callId);if(!e?.rootSpan)return;const{telemetry:n}=e,o=e.operationId==="ai.embedMany";e.rootSpan.setAttributes(d(n,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(n,this.supplementalAttributes,{embedding:o?{"ai.embeddings":{output:()=>t.embedding.map(r=>JSON.stringify(r))}}:{"ai.embedding":{output:()=>JSON.stringify(t.embedding)}}})})),e.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>t.values.map(p=>JSON.stringify(p))}}})}),a=`embeddings ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.embedSpans.set(t.embedCallId,{span:i,context:s})}onEmbedEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.embedSpans.get(t.embedCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e;o.setAttributes(d(r,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(r,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>t.embeddings.map(a=>JSON.stringify(a))}}})})),o.end(),e.embedSpans.delete(t.embedCallId)}onRerankOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=d(e,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${t.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),s=l.trace.setSpan(l.context.active(),i);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:i,rootContext:s,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onRerankOperationEnd(t){const e=this.getCallState(t.callId);e?.rootSpan&&(e.rootSpan.end(),this.cleanupCallState(t.callId))}onRerankStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.rerankSpan={span:i,context:s}}onRerankEnd(t){const e=this.getCallState(t.callId);if(!e?.rerankSpan)return;const{span:n}=e.rerankSpan,{telemetry:o}=e;n.setAttributes(m(o,this.supplementalAttributes,{reranking:{"ai.ranking.type":t.documentsType,"ai.ranking":{output:()=>t.ranking.map(r=>JSON.stringify(r))}}})),n.end(),e.rerankSpan=void 0}onAbort(t){const e=this.getCallState(t.callId);if(e?.rootSpan){for(const{span:n}of e.toolSpans.values())n.end();e.toolSpans.clear(),e.inferenceSpan&&(e.inferenceSpan.end(),e.inferenceSpan=void 0,e.inferenceContext=void 0),e.stepSpan&&(e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0);for(const{span:n}of e.embedSpans.values())n.end();e.embedSpans.clear(),e.rerankSpan&&(e.rerankSpan.span.end(),e.rerankSpan=void 0),e.rootSpan.end(),this.cleanupCallState(t.callId)}}onError(t){var e;const n=t;if(!n?.callId)return;const o=this.getCallState(n.callId);if(!o?.rootSpan)return;const r=(e=n.error)!=null?e:t;for(const{span:a}of o.toolSpans.values())h(a,r),a.end();o.toolSpans.clear(),o.inferenceSpan&&(h(o.inferenceSpan,r),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0),o.stepSpan&&(h(o.stepSpan,r),o.stepSpan.end(),o.stepSpan=void 0,o.stepContext=void 0);for(const{span:a}of o.embedSpans.values())h(a,r),a.end();o.embedSpans.clear(),o.rerankSpan&&(h(o.rerankSpan.span,r),o.rerankSpan.span.end(),o.rerankSpan=void 0),h(o.rootSpan,r),o.rootSpan.end(),this.cleanupCallState(n.callId)}};function U(t){return y.pruneMessages({messages:t,emptyMessages:"remove",reasoning:"none",toolCalls:`before-last-${l.TOOL_CALL_MESSAGES_TO_KEEP}-messages`})}function B(t){return typeof t=="object"&&t!==null&&"role"in t&&"content"in t}function G(t){return Array.isArray(t)&&t.every(B)}function F(t,{conversationId:e,getModel:n}){let o=0;const r=()=>{const a=n?.();return a?{model_provider:a.provider,model_id:a.modelId}:{}};return{onStepStart:()=>{o+=1},onToolExecutionStart:a=>{t("com.redocly.aiChat.toolCallStarted",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,...r()}])},onToolExecutionEnd:a=>{const i=a.toolOutput.type==="tool-error";t("com.redocly.aiChat.toolCallFinished",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,success:!i,duration_ms:a.toolExecutionMs,...r(),...i&&{error:a.toolOutput.error instanceof Error?a.toolOutput.error.message:String(a.toolOutput.error)}}])},onStart:a=>{o=0,t("com.redocly.aiChat.conversationStarted",[{...l.createResource("conversation",e,"ai"),model_provider:"provider"in a?a.provider:"unknown",model_id:"modelId"in a?a.modelId:"unknown"}])},onEnd:a=>{if(!("steps"in a))return;const i=a.usage;t("com.redocly.aiChat.conversationFinished",[{...l.createResource("conversation",e,"ai"),model_provider:a.model.provider,model_id:a.model.modelId,success:!0,step_count:a.steps.length,finish_reason:a.finishReason,input_tokens:i.inputTokens,output_tokens:i.outputTokens,total_tokens:i.totalTokens}])}}}function V(t,e){const n=()=>l.trace.getSpan(l.context.active())?l.context.active():e;return{startSpan:(o,r,a)=>t.startSpan(o,r,a??e),startActiveSpan:((o,r,a,i)=>{if(typeof r=="function")return t.startActiveSpan(o,{},n(),r);if(typeof a=="function")return t.startActiveSpan(o,r,n(),a);if(i)return t.startActiveSpan(o,r,a,i);throw new Error("withParentContext: invalid startActiveSpan invocation")})}}class H{model;tools;toolLoopAgent;maxSteps;context=[];systemInstructions=j.getSystemInstructions();getActiveStateMessage;constructor(e){const{activeConversationId:n,onFinish:o,onStepFinish:r,tools:a}=e;this.maxSteps=e.maxSteps??l.DEFAULT_MAX_STEPS,this.getActiveStateMessage=e.getActiveStateMessage,this.model=this.createModel(e.model);const i=({stepNumber:c,messages:g})=>{const u=[],f=this.buildActiveStateMessage();return f&&u.push({role:"user",content:f}),c===this.maxSteps-1&&u.push({role:"user",content:T.LAST_STEP_PROMPT}),u.length===0?void 0:{messages:[...g,...u]}},s=c=>{const g=c.messages?this.prepareMessages(c.messages):void 0,u=c.prompt?this.preparePrompt(c.prompt):void 0;return{...c,model:this.model,messages:g,prompt:u,instructions:[...this.systemInstructions,...this.context],tools:this.tools??c.tools}},p=new z({...e.parentCtx&&{tracer:V(l.trace.getTracer("ai"),e.parentCtx)}});this.toolLoopAgent=new y.ToolLoopAgent({model:this.model,tools:a,stopWhen:y.isStepCount(this.maxSteps),onStepFinish:r,onFinish:o,maxOutputTokens:e.maxOutputTokens,maxRetries:e.maxRetries??l.DEFAULT_MAX_RETRIES,prepareStep:i,prepareCall:s,telemetry:{isEnabled:!0,recordInputs:!0,recordOutputs:!0,functionId:"replay-ai-chat",integrations:[p,F(e.sendEvent,{conversationId:n,getModel:()=>({provider:this.model.provider,modelId:this.model.modelId})})]}})}createModel(e){return y.createModel(e)}setModel(e){this.model=this.createModel(e)}getAgent(){return this.toolLoopAgent}addContext(e){this.context.push(...e)}registerTools(e){this.tools=e}async generateTitle(e,n){return y.streamText({model:this.model,system:T.CONVERSATION_TITLE_PROMPT,prompt:e,temperature:0,abortSignal:n}).text}buildActiveStateMessage(){if(!this.getActiveStateMessage)return null;try{return this.getActiveStateMessage()||null}catch(e){return console.error(e),null}}prepareMessages(e){return U(e)}preparePrompt(e){return G(e)?this.prepareMessages(e):e}}exports.AgentLoop=H;
@@ -1,4 +1,4 @@
1
- import { U as n, F as d, V as i } from "./replay-index-B2RZCGOF.js";
1
+ import { W as n, H as d, X as i } from "./replay-index-BizzVzWT.js";
2
2
  function A() {
3
3
  return `aichat_${n()}`;
4
4
  }
@@ -1 +1 @@
1
- "use strict";const i=require("./replay-index-D85qPcEF.js");function d(){return`aichat_${i.ulid()}`}function u(){return`aimsg_${i.ulid()}`}function c(){return`aimpt_${i.ulid()}`}function l(e){return{id:e.id,title:e.title??void 0,modelConfig:e.modelConfig,messages:e.messages.map(g),createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function g(e){return{id:e.uiId,role:e.role,metadata:e.metadata,parts:e.parts.map(C)}}function C(e){return e.self}function f(e){const a=e.id;return{id:a,title:e.title,modelConfig:e.modelConfig,messages:e.messages.map((t,r)=>n(a,r,t))}}function n(e,a,t,r=u()){return{id:r,uiId:t.id,role:t.role,metadata:t.metadata,aiChatId:e,indexWithinInsertBatch:a,parts:t.parts.map((s,o)=>I(r,o,s))}}function I(e,a,t){return{id:c(),text:t.type==="text"?t.text:null,index:a,self:t,aiMessageId:e}}function A(e){return{id:e.id,title:e.title,modelConfig:h(e.model),messages:e.messages.map(p)}}function h(e){switch(e.provider){case i.AI_PROVIDERS.OPENAI:case i.AI_PROVIDERS.ANTHROPIC:case i.AI_PROVIDERS.GEMINI:return{provider:e.provider,modelId:e.modelId};case i.REUNITE_AI_PROVIDER:return{provider:e.provider,baseUrl:e.baseUrl};default:throw new Error("Cannot create model config")}}function p(e){return{...e,parts:e.parts.filter(a=>a.type!=="file")}}exports.buildPersistableUiChat=A;exports.convertAiChatRowToUiChat=l;exports.convertUiChatToAiChatRow=f;exports.convertUiMessageToAiChatMessage=n;exports.generateAiChatId=d;
1
+ "use strict";const i=require("./replay-index-D3evrr0U.js");function d(){return`aichat_${i.ulid()}`}function u(){return`aimsg_${i.ulid()}`}function c(){return`aimpt_${i.ulid()}`}function l(e){return{id:e.id,title:e.title??void 0,modelConfig:e.modelConfig,messages:e.messages.map(g),createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function g(e){return{id:e.uiId,role:e.role,metadata:e.metadata,parts:e.parts.map(C)}}function C(e){return e.self}function f(e){const a=e.id;return{id:a,title:e.title,modelConfig:e.modelConfig,messages:e.messages.map((t,r)=>n(a,r,t))}}function n(e,a,t,r=u()){return{id:r,uiId:t.id,role:t.role,metadata:t.metadata,aiChatId:e,indexWithinInsertBatch:a,parts:t.parts.map((s,o)=>I(r,o,s))}}function I(e,a,t){return{id:c(),text:t.type==="text"?t.text:null,index:a,self:t,aiMessageId:e}}function A(e){return{id:e.id,title:e.title,modelConfig:h(e.model),messages:e.messages.map(p)}}function h(e){switch(e.provider){case i.AI_PROVIDERS.OPENAI:case i.AI_PROVIDERS.ANTHROPIC:case i.AI_PROVIDERS.GEMINI:return{provider:e.provider,modelId:e.modelId};case i.REUNITE_AI_PROVIDER:return{provider:e.provider,baseUrl:e.baseUrl};default:throw new Error("Cannot create model config")}}function p(e){return{...e,parts:e.parts.filter(a=>a.type!=="file")}}exports.buildPersistableUiChat=A;exports.convertAiChatRowToUiChat=l;exports.convertUiChatToAiChatRow=f;exports.convertUiMessageToAiChatMessage=n;exports.generateAiChatId=d;