@redocly/replay 0.28.0-next.4 → 0.28.0-next.6

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 (64) hide show
  1. package/dist/{replay-AiChatProvider-BIplPHOS.js → replay-AiChatProvider-Bj2P_hdU.js} +371 -369
  2. package/dist/replay-AiChatProvider-GeumgtIo.js +6 -0
  3. package/dist/{replay-AiChatSqliteDBStorage-Bay95FHW.js → replay-AiChatSqliteDBStorage-0M2Ejnzu.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-C-rkQ3jG.js → replay-AiChatSqliteDBStorage-BWJl1qdO.js} +1 -1
  5. package/dist/{replay-AiPanel-DU5aVA3q.js → replay-AiPanel-DfOpKMDQ.js} +709 -712
  6. package/dist/replay-AiPanel-ON_QfwBN.js +742 -0
  7. package/dist/replay-FileWatcher-04GlEkra.js +360 -0
  8. package/dist/replay-FileWatcher-B-T0jz_R.js +1 -0
  9. package/dist/{replay-SemanticSearchService-Dk4UTm2r.js → replay-SemanticSearchService-BQgdj2wy.js} +1 -1
  10. package/dist/{replay-SemanticSearchService-BWwCFW3F.js → replay-SemanticSearchService-CPIb_cUk.js} +7 -7
  11. package/dist/{replay-SqliteDBStorage-BFdjYsG7.js → replay-SqliteDBStorage-Bt2xXqei.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-DGQjzDy4.js → replay-SqliteDBStorage-vehgvWXZ.js} +1 -1
  13. package/dist/{replay-TauriFileSystemAdapter-CLzYSck7.js → replay-TauriFileSystemAdapter-D2yxrS6Q.js} +1 -1
  14. package/dist/{replay-TauriFileSystemAdapter-C8k9RvT1.js → replay-TauriFileSystemAdapter-YLdtT-Xp.js} +1 -1
  15. package/dist/{replay-TauriRootStorage-C1MIH5ji.js → replay-TauriRootStorage-BE6RmQfE.js} +162 -165
  16. package/dist/replay-TauriRootStorage-DcENVsBJ.js +1 -0
  17. package/dist/{replay-agent-loop-BoEw65rR.js → replay-agent-loop-CvopOugZ.js} +13 -13
  18. package/dist/{replay-agent-loop-Cm1iS9G2.js → replay-agent-loop-UwDSVh-4.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-IZNFNXug.js → replay-ai-chat-mappers-B7fm-v_w.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-Csm9vJrG.js → replay-ai-chat-mappers-yKBypIXh.js} +1 -1
  21. package/dist/{replay-create-model-BqvD-0wF.js → replay-create-model-CHahxEJy.js} +3 -3
  22. package/dist/{replay-create-model-Y9UJSztb.js → replay-create-model-CyBZMAWB.js} +4 -4
  23. package/dist/{replay-db-BImXgUGU.js → replay-db-CifZMdnr.js} +5 -5
  24. package/dist/{replay-db-C7FD3opa.js → replay-db-EWL-uAt-.js} +1 -1
  25. package/dist/{replay-external-resolver-CjM7Da6t.js → replay-external-resolver-D5fSfJEm.js} +1 -1
  26. package/dist/{replay-external-resolver-Bj3sLTnz.js → replay-external-resolver-G11iwLVZ.js} +2 -2
  27. package/dist/{replay-index-Dxk-kqkZ.js → replay-index-B2NUTBd8.js} +1 -1
  28. package/dist/{replay-index-CKRKzXMt.js → replay-index-B3MQaIS-.js} +1 -1
  29. package/dist/replay-index-Coy4kD_x.js +7009 -0
  30. package/dist/{replay-index-DJwfdo0s.js → replay-index-CqRiEj9e.js} +1 -1
  31. package/dist/{replay-index-DlTloE6S.js → replay-index-D0mbH_TN.js} +1 -1
  32. package/dist/{replay-index-Cp06WK82.js → replay-index-DDqKE6bs.js} +5 -5
  33. package/dist/{replay-index-xheWgsnj.js → replay-index-DrI9ZFwH.js} +2 -2
  34. package/dist/{replay-index-BH8cTSEK.js → replay-index-Dx8O3ZoA.js} +68783 -67874
  35. package/dist/{replay-lint-BIbkYU09.js → replay-lint-BiOcDIDr.js} +3 -3
  36. package/dist/{replay-lint--iBW-6Vj.js → replay-lint-CAo2fuiZ.js} +3 -3
  37. package/dist/{replay-lint-graphql-EXBI8I89.js → replay-lint-graphql-DAa8UNRg.js} +1 -1
  38. package/dist/{replay-lint-graphql-2b4GIER6.js → replay-lint-graphql-DzI2rUbR.js} +1 -1
  39. package/dist/replay-periodic-revalidation-D18ihfUc.js +1 -0
  40. package/dist/replay-periodic-revalidation-w7mrtjYg.js +22 -0
  41. package/dist/{replay-resolve-D9BUvjqv.js → replay-resolve-CojDRP37.js} +1 -1
  42. package/dist/{replay-resolve-B5yIfyuT.js → replay-resolve-DgAthAfi.js} +1 -1
  43. package/dist/{replay-respect-run-DNFoFnJU.js → replay-respect-run-3ukV7LMg.js} +1 -1
  44. package/dist/{replay-respect-run-Bx46aUHi.js → replay-respect-run-DNvB8rLX.js} +3 -3
  45. package/dist/replay-tauri-path-DM8PdMK8.js +22 -0
  46. package/dist/{replay-tauri-path-C8GiFO5s.js → replay-tauri-path-kr9DtxLs.js} +1 -1
  47. package/dist/{replay-useAiChatQueries-BTuu2xLG.js → replay-useAiChatQueries-BULoKr4E.js} +1564 -1395
  48. package/dist/replay-useAiChatQueries-BdjsFz1P.js +215 -0
  49. package/dist/{replay-validate-key-D4M7QvCw.js → replay-validate-key-CGmguj5X.js} +1 -1
  50. package/dist/{replay-validate-key-CjcIElmE.js → replay-validate-key-DzseOR5a.js} +2 -2
  51. package/dist/replay.cjs +1 -1
  52. package/dist/replay.d.ts +3 -3
  53. package/dist/replay.js +10 -10
  54. package/package.json +12 -5
  55. package/dist/replay-AiChatProvider-TF1u9E5L.js +0 -6
  56. package/dist/replay-AiPanel-DzGN1t86.js +0 -742
  57. package/dist/replay-FileWatcher-XMkIoDEA.js +0 -1
  58. package/dist/replay-FileWatcher-iYbHpwCv.js +0 -352
  59. package/dist/replay-TauriRootStorage-CiGY8MO6.js +0 -1
  60. package/dist/replay-index-BuYoH96w.js +0 -6982
  61. package/dist/replay-periodic-revalidation-BoyLQHtg.js +0 -1
  62. package/dist/replay-periodic-revalidation-Dsp-n7ui.js +0 -21
  63. package/dist/replay-tauri-path-BVoW6En0.js +0 -22
  64. package/dist/replay-useAiChatQueries-BDgjmzz-.js +0 -215
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./replay-index-Coy4kD_x.js"),Y=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-D2yxrS6Q.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,h){this.fn=a,this.context=u,this.once=h||!1}function o(a,u,h,f,g){if(typeof h!="function")throw new TypeError("The listener must be a function");var y=new n(h,f||a,g),v=t?t+u:u;return a._events[v]?a._events[v].fn?a._events[v]=[a._events[v],y]:a._events[v].push(y):(a._events[v]=y,a._eventsCount++),a}function d(a,u){--a._eventsCount===0?a._events=new r:delete a._events[u]}function c(){this._events=new r,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],h,f;if(this._eventsCount===0)return u;for(f in h=this._events)e.call(h,f)&&u.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(h)):u},c.prototype.listeners=function(u){var h=t?t+u:u,f=this._events[h];if(!f)return[];if(f.fn)return[f.fn];for(var g=0,y=f.length,v=new Array(y);g<y;g++)v[g]=f[g].fn;return v},c.prototype.listenerCount=function(u){var h=t?t+u:u,f=this._events[h];return f?f.fn?1:f.length:0},c.prototype.emit=function(u,h,f,g,y,v){var b=t?t+u:u;if(!this._events[b])return!1;var l=this._events[b],T=arguments.length,Q,w;if(l.fn){switch(l.once&&this.removeListener(u,l.fn,void 0,!0),T){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,h),!0;case 3:return l.fn.call(l.context,h,f),!0;case 4:return l.fn.call(l.context,h,f,g),!0;case 5:return l.fn.call(l.context,h,f,g,y),!0;case 6:return l.fn.call(l.context,h,f,g,y,v),!0}for(w=1,Q=new Array(T-1);w<T;w++)Q[w-1]=arguments[w];l.fn.apply(l.context,Q)}else{var ae=l.length,x;for(w=0;w<ae;w++)switch(l[w].once&&this.removeListener(u,l[w].fn,void 0,!0),T){case 1:l[w].fn.call(l[w].context);break;case 2:l[w].fn.call(l[w].context,h);break;case 3:l[w].fn.call(l[w].context,h,f);break;case 4:l[w].fn.call(l[w].context,h,f,g);break;default:if(!Q)for(x=1,Q=new Array(T-1);x<T;x++)Q[x-1]=arguments[x];l[w].fn.apply(l[w].context,Q)}}return!0},c.prototype.on=function(u,h,f){return o(this,u,h,f,!1)},c.prototype.once=function(u,h,f){return o(this,u,h,f,!0)},c.prototype.removeListener=function(u,h,f,g){var y=t?t+u:u;if(!this._events[y])return this;if(!h)return d(this,y),this;var v=this._events[y];if(v.fn)v.fn===h&&(!g||v.once)&&(!f||v.context===f)&&d(this,y);else{for(var b=0,l=[],T=v.length;b<T;b++)(v[b].fn!==h||g&&!v[b].once||f&&v[b].context!==f)&&l.push(v[b]);l.length?this._events[y]=l.length===1?l[0]:l:d(this,y)}return this},c.prototype.removeAllListeners=function(u){var h;return u?(h=t?t+u:u,this._events[h]&&d(this,h)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=t,c.EventEmitter=c,s.exports=c})(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,c)=>{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&&c(H(a)),a.addEventListener("abort",()=>{c(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(),c(u)},e),(async()=>{try{d(await s)}catch(a){c(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 m=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})`);m(this,L,e.carryoverConcurrencyCount,"f"),m(this,M,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),m(this,R,e.intervalCap,"f"),m(this,N,e.interval,"f"),m(this,P,new e.queueClass,"f"),m(this,k,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,m(this,q,e.throwOnTimeout===!0,"f"),m(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})`);m(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,c;m(this,S,(d=i(this,S,"f"),d++,d),"f"),m(this,I,(c=i(this,I,"f"),c++,c),"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")?(m(this,C,!1,"f"),i(this,_,"m",$).call(this),this):this}pause(){m(this,C,!0,"f")}clear(){m(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;m(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),m(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)m(this,I,i(this,L,"f")?i(this,S,"f"):0,"f");else return i(this,O,"f")===void 0&&m(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")),m(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||(m(this,E,setInterval(()=>{i(this,_,"m",K).call(this)},i(this,N,"f")),"f"),m(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")),m(this,E,void 0,"f")),m(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 ve{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 c=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...c,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 me 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 ve(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:c}=await this.detectProjectFiles(e);await this.loadAndParseApis(d,e);const u=(await this.loadAndParseCollections(c,e)).filter(f=>f!==null),h=this.apiLoader.getAll();return e?.setAttribute("status","completed"),e?.setStatus(p.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:n,environments:o,apis:h,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(c){return console.info(`Error parsing YAML/JSON file ${d.absolute_path}:`,c),await p.reportParseError(d.relative_path,c),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 c=p.yaml.load(d);if(typeof c!="object"||c===null||typeof c.arazzo!="string")return await p.clearNotificationsForSource(o.relative_path),null;const a=[];await Promise.all(c.sourceDescriptions?.map(async f=>{const g=f.type,y=f.url,v=!g||g==="openapi",b=await p.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:y,collectionId:o.relative_path});if(v){const l=await this.apiLoader.get(b);l&&a.push(l)}}));const u=await p.PathUtils.join(this.project.userFilesDir,o.relative_path),h=await this.collectionsStorage.parse({uri:o.relative_path,type:p.SourceType.FS,content:c,fileDependencies:new Set([u])},a);return await p.clearNotificationsForSource(o.relative_path),h}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=me;
@@ -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-Y9UJSztb.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-BH8cTSEK.js";
3
- import { g as U } from "./replay-db-BImXgUGU.js";
4
- import { L as G, C as F } 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-CyBZMAWB.js";
2
+ import { O as g, Q as _, Z as S, e as M, _ as W, d as I, $ as z, a0 as K } from "./replay-index-Dx8O3ZoA.js";
3
+ import { g as U } from "./replay-db-CifZMdnr.js";
4
+ import { L as G, C as B } 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 V(t) {
44
+ function F(t) {
45
45
  var e, n, o, s, a;
46
46
  switch (t.type) {
47
47
  case "text":
@@ -126,14 +126,14 @@ function V(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 B(t) {
129
+ function V(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(V);
136
+ const n = e.content.map(F);
137
137
  return { role: e.role, parts: n };
138
138
  });
139
139
  }
@@ -406,7 +406,7 @@ function p(t, e) {
406
406
  }
407
407
  return n;
408
408
  }
409
- var Y = {
409
+ var Z = {
410
410
  usage: !1,
411
411
  providerMetadata: !1,
412
412
  embedding: !1,
@@ -416,10 +416,10 @@ var Y = {
416
416
  toolChoice: !1,
417
417
  schema: !1
418
418
  };
419
- function Z(t) {
419
+ function Y(t) {
420
420
  var e, n, o, s, a, r, i, u;
421
421
  return {
422
- ...Y,
422
+ ...Z,
423
423
  usage: (e = t.usage) != null ? e : !1,
424
424
  providerMetadata: (n = t.providerMetadata) != null ? n : !1,
425
425
  embedding: (o = t.embedding) != null ? o : !1,
@@ -484,7 +484,7 @@ var nt = class {
484
484
  constructor(t = {}) {
485
485
  this.callStates = /* @__PURE__ */ new Map();
486
486
  var e;
487
- this.tracer = (e = t.tracer) != null ? e : g.getTracer("gen_ai"), this.supplementalAttributes = Z(t), this.enrichSpan = t.enrichSpan;
487
+ this.tracer = (e = t.tracer) != null ? e : g.getTracer("gen_ai"), this.supplementalAttributes = Y(t), this.enrichSpan = t.enrichSpan;
488
488
  }
489
489
  getCallState(t) {
490
490
  return this.callStates.get(t);
@@ -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(B(t.promptMessages)) : void 0
736
+ input: () => t.promptMessages ? JSON.stringify(V(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: F,
1509
+ system: B,
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-BqvD-0wF.js"),l=require("./replay-index-BuYoH96w.js"),j=require("./replay-db-C7FD3opa.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-CHahxEJy.js"),l=require("./replay-index-Coy4kD_x.js"),j=require("./replay-db-EWL-uAt-.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 +1 @@
1
- "use strict";const i=require("./replay-index-BuYoH96w.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-Coy4kD_x.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,4 +1,4 @@
1
- import { W as n, H as d, X as i } from "./replay-index-BH8cTSEK.js";
1
+ import { a1 as n, U as d, a2 as i } from "./replay-index-Dx8O3ZoA.js";
2
2
  function A() {
3
3
  return `aichat_${n()}`;
4
4
  }