@redocly/replay 0.28.0-next.8 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{replay-AiChatProvider--1WugvKf.js → replay-AiChatProvider-BRqjyy2W.js} +2 -2
- package/dist/{replay-AiChatProvider-BJdxRVOc.js → replay-AiChatProvider-DUVoLgY2.js} +128 -130
- package/dist/{replay-AiChatSqliteDBStorage-D9fgt_9s.js → replay-AiChatSqliteDBStorage-0evx56pl.js} +6 -6
- package/dist/{replay-AiChatSqliteDBStorage-DbGtw6xx.js → replay-AiChatSqliteDBStorage-C5AnRloD.js} +1 -1
- package/dist/{replay-AiPanel-BU8oG0pD.js → replay-AiPanel-CMjVD12K.js} +77 -77
- package/dist/{replay-AiPanel-BYOLZjQX.js → replay-AiPanel-PVgJioX3.js} +2 -2
- package/dist/replay-FileWatcher-CFYprlWN.js +364 -0
- package/dist/replay-FileWatcher-DGLwO5Kd.js +1 -0
- package/dist/{replay-HistorySqliteDBStorage-CtF6-vY8.js → replay-HistorySqliteDBStorage-Bi5vBQ2T.js} +2 -2
- package/dist/{replay-SemanticSearchService-DRDdGJkI.js → replay-SemanticSearchService-Bh5xYa91.js} +22 -26
- package/dist/replay-SemanticSearchService-CulKCCNl.js +1 -0
- package/dist/{replay-SqliteDBStorage-D9Oeu_XC.js → replay-SqliteDBStorage-Bz0muHEk.js} +49 -49
- package/dist/{replay-SqliteDBStorage-B3zO7RGD.js → replay-SqliteDBStorage-CVHRAsPD.js} +1 -1
- package/dist/{replay-StepContextSqliteDBStorage-BfAAKDwA.js → replay-StepContextSqliteDBStorage-BkB2NM27.js} +2 -2
- package/dist/replay-TauriFileSystemAdapter-B163-f2D.js +108 -0
- package/dist/replay-TauriFileSystemAdapter-D4bOmvzP.js +1 -0
- package/dist/{replay-TauriRootStorage-XIJpsp6_.js → replay-TauriRootStorage-2MPQE-3f.js} +159 -155
- package/dist/replay-TauriRootStorage-CjWUrnWz.js +1 -0
- package/dist/{replay-agent-loop-DxK1tiVw.js → replay-agent-loop-BgYyBo9e.js} +9 -9
- package/dist/{replay-agent-loop-IDavXm8f.js → replay-agent-loop-DYDFXAZj.js} +1 -1
- package/dist/{replay-ai-chat-mappers-B-_eSMi4.js → replay-ai-chat-mappers-BEwNRQPV.js} +3 -3
- package/dist/{replay-ai-chat-mappers-BmvAc4xt.js → replay-ai-chat-mappers-CMtNqQHX.js} +1 -1
- package/dist/{replay-ai-message-parts.schema-E9u9-nqr.js → replay-ai-message-parts.schema-DKLf0SiG.js} +1 -1
- package/dist/{replay-create-model-CscK0cT1.js → replay-create-model-B2ZsGTjs.js} +3 -3
- package/dist/{replay-create-model-CIY7WZ1P.js → replay-create-model-DPxfOEfv.js} +4 -4
- package/dist/{replay-db-e_3o5e3f.js → replay-db-C9iqyMet.js} +1 -1
- package/dist/{replay-db-C_cdHXEt.js → replay-db-D4-LmLRk.js} +5 -5
- package/dist/{replay-external-resolver-nuL3ajF5.js → replay-external-resolver-BXgVrfzk.js} +7 -7
- package/dist/{replay-external-resolver-BmOmF-DG.js → replay-external-resolver-CTUbNZGW.js} +1 -1
- package/dist/{replay-history.schema-5ce6X0R1.js → replay-history.schema-B0lLwmdG.js} +3 -3
- package/dist/{replay-index-DDt4LOBo.js → replay-index-4TEahAPK.js} +21968 -21367
- package/dist/{replay-index-DjdDUkfV.js → replay-index-B4U7iZuq.js} +46 -46
- package/dist/replay-index-B8O3wYqo.js +1 -0
- package/dist/{replay-index-etIeWhnn.js → replay-index-Bdg7noSD.js} +1 -1
- package/dist/replay-index-CG9VN2JQ.js +4 -0
- package/dist/{replay-index-E3Eu6_jY.js → replay-index-DcC173cC.js} +1 -1
- package/dist/{replay-index-B8Zfn7JD.js → replay-index-Nz5obVS5.js} +1139 -1141
- package/dist/{replay-index-DcbwI4wD.js → replay-index-q63USe25.js} +1 -1
- package/dist/{replay-indexes-CfsvVMi_.js → replay-indexes-B3PJtgeh.js} +43 -43
- package/dist/{replay-lint-DVAifLdU.js → replay-lint-4XFKTmSY.js} +97 -97
- package/dist/{replay-lint-graphql-U_VxwRr1.js → replay-lint-graphql-BsBWkZ6L.js} +1 -1
- package/dist/{replay-lint-graphql-D1qaeEmu.js → replay-lint-graphql-De2eDZnT.js} +1 -1
- package/dist/{replay-lint-BjrmIhuZ.js → replay-lint-s7ylMBWz.js} +6111 -6074
- package/dist/replay-periodic-revalidation-BMFP7f-u.js +1 -0
- package/dist/{replay-periodic-revalidation-BtEKdEKa.js → replay-periodic-revalidation-DJbblUef.js} +4 -5
- package/dist/{replay-resolve-C97SfUAB.js → replay-resolve-BtNxNrKo.js} +123 -123
- package/dist/{replay-resolve-BYJosLqD.js → replay-resolve-BueEsOnR.js} +1 -1
- package/dist/{replay-respect-run-CW5xFLKz.js → replay-respect-run-B_dJjlti.js} +1 -1
- package/dist/{replay-respect-run-3FHTVHvs.js → replay-respect-run-Dfpbcsns.js} +3 -3
- package/dist/replay-step-context.schema-BOprzd6Z.js +21 -0
- package/dist/{replay-tauri-path-CMpWmGvW.js → replay-tauri-path-Bht3XIt7.js} +1 -1
- package/dist/replay-tauri-path-CiuYXh_j.js +22 -0
- package/dist/replay-useAiChatQueries-02CRdEPJ.js +215 -0
- package/dist/{replay-useAiChatQueries-DhTcllVx.js → replay-useAiChatQueries-D2hh5omV.js} +1039 -996
- package/dist/{replay-validate-key-Dj_UT2WG.js → replay-validate-key-ALwOF1Ux.js} +1 -1
- package/dist/{replay-validate-key-DJ_1khxq.js → replay-validate-key-B7fbWbfv.js} +2 -2
- package/dist/replay.cjs +1 -1
- package/dist/replay.d.ts +5 -0
- package/dist/replay.js +15 -15
- package/package.json +6 -6
- package/dist/replay-FileWatcher-BrhE0AP6.js +0 -1
- package/dist/replay-FileWatcher-JoqPJECh.js +0 -360
- package/dist/replay-SemanticSearchService-BgQ1HMcT.js +0 -1
- package/dist/replay-TauriFileSystemAdapter-CxHFFCmk.js +0 -1
- package/dist/replay-TauriFileSystemAdapter-DJETGEY7.js +0 -99
- package/dist/replay-TauriRootStorage-BSQQcFgG.js +0 -1
- package/dist/replay-index-C_DfEx-H.js +0 -1
- package/dist/replay-index-Da2H-hpA.js +0 -25
- package/dist/replay-periodic-revalidation-C3eLm7Mw.js +0 -1
- package/dist/replay-step-context.schema-DBk4jufr.js +0 -21
- package/dist/replay-tauri-path-C-vLbl1V.js +0 -22
- package/dist/replay-useAiChatQueries-CEYDGx9f.js +0 -215
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./replay-index-Nz5obVS5.js"),B=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-D4bOmvzP.js");var U={exports:{}},K;function oe(){return K||(K=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function a(s,u,h){this.fn=s,this.context=u,this.once=h||!1}function o(s,u,h,f,y){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new a(h,f||s,y),v=t?t+u:u;return s._events[v]?s._events[v].fn?s._events[v]=[s._events[v],g]:s._events[v].push(g):(s._events[v]=g,s._eventsCount++),s}function p(s,u){--s._eventsCount===0?s._events=new r:delete s._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 y=0,g=f.length,v=new Array(g);y<g;y++)v[y]=f[y].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,y,g,v){var b=t?t+u:u;if(!this._events[b])return!1;var l=this._events[b],T=arguments.length,F,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,y),!0;case 5:return l.fn.call(l.context,h,f,y,g),!0;case 6:return l.fn.call(l.context,h,f,y,g,v),!0}for(w=1,F=new Array(T-1);w<T;w++)F[w-1]=arguments[w];l.fn.apply(l.context,F)}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,y);break;default:if(!F)for(x=1,F=new Array(T-1);x<T;x++)F[x-1]=arguments[x];l[w].fn.apply(l[w].context,F)}}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,y){var g=t?t+u:u;if(!this._events[g])return this;if(!h)return p(this,g),this;var v=this._events[g];if(v.fn)v.fn===h&&(!y||v.once)&&(!f||v.context===f)&&p(this,g);else{for(var b=0,l=[],T=v.length;b<T;b++)(v[b].fn!==h||y&&!v[b].once||f&&v[b].context!==f)&&l.push(v[b]);l.length?this._events[g]=l.length===1?l[0]:l:p(this,g)}return this},c.prototype.removeAllListeners=function(u){var h;return u?(h=t?t+u:u,this._events[h]&&p(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,n.exports=c})(U)),U.exports}var ue=oe();const le=d.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 H=n=>globalThis.DOMException===void 0?new ce(n):new DOMException(n),J=n=>{const e=n.reason===void 0?H("This operation was aborted."):n.reason;return e instanceof Error?e:H(e)};function he(n,e,t,r){let a;const o=new Promise((p,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){p(n);return}if(r={customTimers:{setTimeout,clearTimeout},...r},r.signal){const{signal:s}=r;s.aborted&&c(J(s)),s.addEventListener("abort",()=>{c(J(s))})}a=r.customTimers.setTimeout.call(void 0,()=>{const s=`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(s);typeof n.cancel=="function"&&n.cancel(),c(u)},e),(async()=>{try{p(await n)}catch(s){c(s)}finally{r.customTimers.clearTimeout.call(void 0,a)}})()});return o.clear=()=>{clearTimeout(a),a=void 0},o}function fe(n,e,t){let r=0,a=n.length;for(;a>0;){const o=Math.trunc(a/2);let p=r+o;t(n[p],e)<=0?(r=++p,a-=o+1):a=o}return r}var Q=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},A;class de{constructor(){A.set(this,[])}enqueue(e,t){t={priority:0,...t};const r={priority:t.priority,run:e};if(this.size&&Q(this,A,"f")[this.size-1].priority>=t.priority){Q(this,A,"f").push(r);return}const a=fe(Q(this,A,"f"),r,(o,p)=>p.priority-o.priority);Q(this,A,"f").splice(a,0,r)}dequeue(){const e=Q(this,A,"f").shift();return e?.run}filter(e){return Q(this,A,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return Q(this,A,"f").length}}A=new WeakMap;var m=function(n,e,t,r,a){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!a:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?a.call(n,t):a?a.value=t:e.set(n,t),t},i=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},_,N,L,I,j,M,z,E,O,P,R,S,W,C,k,X,Z,ie,ee,te,D,Y,V,$,ne,q;class se extends Error{}class pe extends le{constructor(e){var t,r,a,o;if(super(),_.add(this),N.set(this,void 0),L.set(this,void 0),I.set(this,0),j.set(this,void 0),M.set(this,void 0),z.set(this,0),E.set(this,void 0),O.set(this,void 0),P.set(this,void 0),R.set(this,void 0),S.set(this,0),W.set(this,void 0),C.set(this,void 0),k.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=(a=e.interval)===null||a===void 0?void 0:a.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);m(this,N,e.carryoverConcurrencyCount,"f"),m(this,L,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),m(this,j,e.intervalCap,"f"),m(this,M,e.interval,"f"),m(this,P,new e.queueClass,"f"),m(this,R,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,m(this,k,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,k,"f"),...t},new Promise((r,a)=>{i(this,P,"f").enqueue(async()=>{var o,p,c;m(this,S,(p=i(this,S,"f"),p++,p),"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 se("The task was aborted.");let s=e({signal:t.signal});t.timeout&&(s=he(Promise.resolve(s),t.timeout)),t.signal&&(s=Promise.race([s,i(this,_,"m",ne).call(this,t.signal)]));const u=await s;r(u),this.emit("completed",u)}catch(s){if(s instanceof re&&!t.throwOnTimeout){r();return}a(s),this.emit("error",s)}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,R,"f")),"f")}async onEmpty(){i(this,P,"f").size!==0&&await i(this,_,"m",q).call(this,"empty")}async onSizeLessThan(e){i(this,P,"f").size<e||await i(this,_,"m",q).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",q).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")}}N=new WeakMap,L=new WeakMap,I=new WeakMap,j=new WeakMap,M=new WeakMap,z=new WeakMap,E=new WeakMap,O=new WeakMap,P=new WeakMap,R=new WeakMap,S=new WeakMap,W=new WeakMap,C=new WeakMap,k=new WeakMap,_=new WeakSet,X=function(){return i(this,L,"f")||i(this,I,"f")<i(this,j,"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",V).call(this),i(this,_,"m",Y).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,N,"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",Y).call(this),!0):!1}}return!1},Y=function(){i(this,L,"f")||i(this,E,"f")!==void 0||(m(this,E,setInterval(()=>{i(this,_,"m",V).call(this)},i(this,M,"f")),"f"),m(this,z,Date.now()+i(this,M,"f"),"f"))},V=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,N,"f")?i(this,S,"f"):0,"f"),i(this,_,"m",$).call(this)},$=function(){for(;i(this,_,"m",D).call(this););},ne=async function(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(new se("The task was aborted."))},{once:!0})})},q=async function(e,t){return new Promise(r=>{const a=()=>{t&&!t()||(this.off(e,a),r())};this.on(e,a)})};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=d.isWebUrl(e)?d.SourceType.WEB:d.SourceType.FS,a=r===d.SourceType.WEB?e:await this.apisStorage.getAbsolutePath(e);try{const{definition:o,fileDependencies:p}=await d.loadAndBundleDefinition(a);if(!o){this.data.set(e,null),await d.clearNotificationsForSource(e);return}const c=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...c,fileDependencies:p}),await d.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 d.clearNotificationsForSource(e);return}console.info("Error loading api "+e,o),await d.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 d.RootStorage{apiLoader;constructor(e,t,r){const a=new G.TauriFileSystemAdapter(e.systemFilesDir),o=new G.TauriFileSystemAdapter(e.userFilesDir);super(a,o,e,!0,{filePaths:d.REDOCLY_CONFIG_FILE_NAMES,basePath:d.REPLAY_ENVIRONMENTS_SECTION_PATH,rebuildWhenUnparseable:!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",[d.createResource("storageOperation","read","storage")],void 0),t=this.telemetry?.startSpan("com.redocly.storage.loadUserState",[d.createResource("storageOperation","loadUserState","storage")],e?.parentCtx),[r,a,o]=await Promise.all([this.activeEnvironmentIdStorage.read(),this.tabsStateStorage.read(),this.environmentsStorage.read()]),p=o.length>0?o:d.cloneObject(d.DEFAULT_ENVIRONMENTS);t?.setAttribute("status","completed"),t?.setAttribute("environmentCount",o.length),t?.setStatus(d.SpanStatusCode.OK),t?.end();const{apiFiles:c,collectionFiles:s}=await this.detectProjectFiles(e);await this.loadAndParseApis(c,e);const h=(await this.loadAndParseCollections(s,e)).filter(y=>y!==null),f=this.apiLoader.getAll();return e?.setAttribute("status","completed"),e?.setStatus(d.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:a,environments:p,apis:f,collections:h}}async detectProjectFiles(e){const t=this.telemetry?.startSpan("com.redocly.storage.detectFiles",[d.createResource("storageOperation","detectFiles","storage")],e?.parentCtx),{api_files:r,collection_files:a}=await d.invoke("fs_scan",{dir:this.project.userFilesDir});return t?.setAttribute("status","completed"),t?.setAttribute("filesCount",r.length+a.length),t?.setAttribute("apiFilesCount",r.length),t?.setAttribute("collectionFilesCount",a.length),t?.setStatus(d.SpanStatusCode.OK),t?.end(),{apiFiles:r,collectionFiles:a}}readEnvironments(){return this.environmentsStorage.read()}deleteApiFromCache(e){this.apiLoader.delete(e)}async loadAndParseApis(e,t,r=!1){const a=this.telemetry?.startSpan("com.redocly.storage.parseApis",[{...d.createResource("storageOperation","parseApis","storage"),apisCount:e.length}],t?.parentCtx),o=await B.promiseMapLimit(e,20,async p=>{try{return await this.apiLoader.load(p.relative_path,r),this.apiLoader.get(p.relative_path)}catch(c){return console.info(`Error parsing YAML/JSON file ${p.absolute_path}:`,c),await d.reportParseError(p.relative_path,c),null}});return a?.setAttribute("status","completed"),a?.setAttribute("parsedApisCount",this.apiLoader.size),a?.setStatus(d.SpanStatusCode.OK),a?.end(),o}async loadAndParseCollections(e,t){const r=this.telemetry?.startSpan("com.redocly.storage.parseCollections",[{...d.createResource("storageOperation","parseCollections","storage"),collectionsCount:e.length}],t?.parentCtx),a=await B.promiseMapLimit(e,20,async o=>{try{const p=await this.userFilesStorage.get(o.relative_path);if(!p)return null;const c=d.yaml.load(p);if(typeof c!="object"||c===null||typeof c.arazzo!="string")return await d.clearNotificationsForSource(o.relative_path),null;const s=[];await Promise.all(c.sourceDescriptions?.map(async f=>{const y=f.type,g=f.url,v=!y||y==="openapi",b=await d.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:g,collectionId:o.relative_path});if(v){const l=await this.apiLoader.get(b);l&&s.push(l)}}));const u=await d.PathUtils.join(this.project.userFilesDir,o.relative_path),h=await this.collectionsStorage.parse({uri:o.relative_path,type:d.SourceType.FS,content:c,fileDependencies:new Set([u])},s);return await d.clearNotificationsForSource(o.relative_path),h}catch(p){return console.info(`Error parsing Arazzo file ${o.relative_path}:`,p),await d.reportParseError(o.relative_path,p),null}});return r?.setAttribute("status","completed"),r?.setAttribute("parsedCollectionsCount",a.length),r?.setStatus(d.SpanStatusCode.OK),r?.end(),a}}exports.TauriRootStorage=me;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as O, p as w, T as L, i as J, c as D, s as $ } from "./replay-create-model-
|
|
2
|
-
import {
|
|
3
|
-
import { g as U } from "./replay-db-
|
|
1
|
+
import { a as O, p as w, T as L, i as J, c as D, s as $ } from "./replay-create-model-DPxfOEfv.js";
|
|
2
|
+
import { z as g, B as _, C as S, E as M, T as z, F as I, G as W, H as K } from "./replay-index-4TEahAPK.js";
|
|
3
|
+
import { g as U } from "./replay-db-D4-LmLRk.js";
|
|
4
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 = [
|
|
@@ -406,7 +406,7 @@ function p(t, e) {
|
|
|
406
406
|
}
|
|
407
407
|
return n;
|
|
408
408
|
}
|
|
409
|
-
var
|
|
409
|
+
var Y = {
|
|
410
410
|
usage: !1,
|
|
411
411
|
providerMetadata: !1,
|
|
412
412
|
embedding: !1,
|
|
@@ -416,10 +416,10 @@ var Z = {
|
|
|
416
416
|
toolChoice: !1,
|
|
417
417
|
schema: !1
|
|
418
418
|
};
|
|
419
|
-
function
|
|
419
|
+
function Z(t) {
|
|
420
420
|
var e, n, o, s, a, r, i, u;
|
|
421
421
|
return {
|
|
422
|
-
...
|
|
422
|
+
...Y,
|
|
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 =
|
|
487
|
+
this.tracer = (e = t.tracer) != null ? e : g.getTracer("gen_ai"), this.supplementalAttributes = Z(t), this.enrichSpan = t.enrichSpan;
|
|
488
488
|
}
|
|
489
489
|
getCallState(t) {
|
|
490
490
|
return this.callStates.get(t);
|
|
@@ -1342,7 +1342,7 @@ function ot(t) {
|
|
|
1342
1342
|
messages: t,
|
|
1343
1343
|
emptyMessages: "remove",
|
|
1344
1344
|
reasoning: "none",
|
|
1345
|
-
toolCalls: `before-last-${
|
|
1345
|
+
toolCalls: `before-last-${z}-messages`
|
|
1346
1346
|
});
|
|
1347
1347
|
}
|
|
1348
1348
|
function at(t) {
|
|
@@ -1444,7 +1444,7 @@ class ct {
|
|
|
1444
1444
|
getActiveStateMessage;
|
|
1445
1445
|
constructor(e) {
|
|
1446
1446
|
const { activeConversationId: n, onFinish: o, onStepFinish: s, tools: a } = e;
|
|
1447
|
-
this.maxSteps = e.maxSteps ??
|
|
1447
|
+
this.maxSteps = e.maxSteps ?? W, this.getActiveStateMessage = e.getActiveStateMessage, this.model = this.createModel(e.model);
|
|
1448
1448
|
const r = ({ stepNumber: d, messages: m }) => {
|
|
1449
1449
|
const l = [], f = this.buildActiveStateMessage();
|
|
1450
1450
|
return f && l.push({ role: "user", content: f }), d === this.maxSteps - 1 && l.push({ role: "user", content: G }), l.length === 0 ? void 0 : { messages: [...m, ...l] };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./replay-create-model-CscK0cT1.js"),l=require("./replay-index-B8Zfn7JD.js"),j=require("./replay-db-e_3o5e3f.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-B2ZsGTjs.js"),l=require("./replay-index-Nz5obVS5.js"),j=require("./replay-db-C9iqyMet.js"),T=require("./replay-defaults-DVvOnvnR.js");function S(t){const e=t.toLowerCase(),n=[["google.vertex","gcp.vertex_ai"],["google.generative-ai","gcp.gemini"],["google-vertex","gcp.vertex_ai"],["amazon-bedrock","aws.bedrock"],["azure-openai","azure.ai.openai"],["anthropic","anthropic"],["openai","openai"],["azure","azure.ai.inference"],["google","gcp.gemini"],["mistral","mistral_ai"],["cohere","cohere"],["bedrock","aws.bedrock"],["groq","groq"],["deepseek","deepseek"],["perplexity","perplexity"],["xai","x_ai"]];for(const[o,r]of n)if(e===o||e.startsWith(o+".")||e.startsWith(o+"-"))return r;return t}function A(t){var e;return(e={"ai.generateText":"invoke_agent","ai.streamText":"invoke_agent","ai.generateObject":"invoke_agent","ai.streamObject":"invoke_agent","ai.embed":"embeddings","ai.embedMany":"embeddings","ai.rerank":"rerank"}[t])!=null?e:t}function O(t){return typeof t=="string"?[{type:"text",content:t}]:Array.isArray(t)?t.map(e=>({type:"text",content:e.content})):[{type:"text",content:t.content}]}function P(t){var e,n,o,r,a;switch(t.type){case"text":return{type:"text",content:t.text};case"reasoning":return{type:"reasoning",content:t.text};case"tool-call":return{type:"tool_call",id:(e=t.toolCallId)!=null?e:null,name:t.toolName,arguments:t.input};case"tool-result":{const i=t.output;let s;return i&&(i.type==="text"||i.type==="error-text"||i.type==="json"||i.type==="error-json"?s=i.value:i.type==="execution-denied"?s={denied:!0,reason:i.reason}:s=i),{type:"tool_call_response",id:(n=t.toolCallId)!=null?n:null,response:s}}case"file":{const i=t.data,s=(()=>{if(typeof i=="object"&&i!==null&&!(i instanceof URL)&&!(i instanceof Uint8Array)&&!(i instanceof ArrayBuffer)&&"type"in i)switch(i.type){case"data":return i.data;case"url":return i.url;case"text":return i.text;default:return""}return i})();let p;if(s instanceof Uint8Array)p=y.convertDataContentToBase64String(s);else if(typeof s=="string"){if(s.startsWith("http://")||s.startsWith("https://"))return{type:"uri",modality:_(t.mediaType),mime_type:(o=t.mediaType)!=null?o:null,uri:s};p=s}else{if(s instanceof URL)return{type:"uri",modality:_(t.mediaType),mime_type:(r=t.mediaType)!=null?r:null,uri:s.toString()};p=String(s)}return{type:"blob",modality:_(t.mediaType),mime_type:(a=t.mediaType)!=null?a:null,content:p}}case"tool-approval-response":return{type:"tool_approval_response",approval_id:t.approvalId,approved:t.approved,reason:t.reason};case"custom":return{type:"custom",kind:t.kind};case"reasoning-file":return{type:String(t.type)};default:return{type:String(t.type)}}}function _(t){return!t||t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"image"}function v(t){return t.filter(e=>e.role!=="system").map(e=>{if(e.role==="system")return{role:"system",parts:[{type:"text",content:e.content}]};const n=e.content.map(P);return{role:e.role,parts:n}})}function k({prompt:t,messages:e}){const n=[];if(typeof t=="string")n.push({role:"user",parts:[{type:"text",content:t}]});else if(Array.isArray(t))for(const o of t){const r=M(o);r&&n.push(r)}if(e)for(const o of e){const r=M(o);r&&n.push(r)}return n}function M(t){if(t.role!=="system"){if(t.role==="user")return typeof t.content=="string"?{role:"user",parts:[{type:"text",content:t.content}]}:{role:"user",parts:t.content.map(n=>{var o,r,a,i,s,p,c,g;switch(n.type){case"text":return{type:"text",content:n.text};case"image":{const u=n.image;return u instanceof URL?{type:"uri",modality:"image",mime_type:(o=n.mediaType)!=null?o:null,uri:u.toString()}:typeof u=="string"?u.startsWith("http://")||u.startsWith("https://")?{type:"uri",modality:"image",mime_type:(r=n.mediaType)!=null?r:null,uri:u}:{type:"blob",modality:"image",mime_type:(a=n.mediaType)!=null?a:null,content:u}:{type:"blob",modality:"image",mime_type:(i=n.mediaType)!=null?i:null,content:y.convertDataContentToBase64String(u)}}case"file":{const u=n.data,f=(()=>{if(typeof u=="object"&&u!==null&&!(u instanceof URL)&&!(u instanceof Uint8Array)&&!(u instanceof ArrayBuffer)&&"type"in u)switch(u.type){case"data":return u.data;case"url":return u.url;case"text":return u.text;default:return""}return u})();return f instanceof URL?{type:"uri",modality:_(n.mediaType),mime_type:(s=n.mediaType)!=null?s:null,uri:f.toString()}:typeof f=="string"?f.startsWith("http://")||f.startsWith("https://")?{type:"uri",modality:_(n.mediaType),mime_type:(p=n.mediaType)!=null?p:null,uri:f}:{type:"blob",modality:_(n.mediaType),mime_type:(c=n.mediaType)!=null?c:null,content:f}:{type:"blob",modality:_(n.mediaType),mime_type:(g=n.mediaType)!=null?g:null,content:y.convertDataContentToBase64String(f)}}default:return{type:String(n.type)}}})};if(t.role==="assistant")return typeof t.content=="string"?{role:"assistant",parts:[{type:"text",content:t.content}]}:{role:"assistant",parts:t.content.map(n=>{var o,r;switch(n.type){case"text":return{type:"text",content:n.text};case"reasoning":return{type:"reasoning",content:n.text};case"tool-call":return{type:"tool_call",id:(o=n.toolCallId)!=null?o:null,name:n.toolName,arguments:n.input};case"tool-result":{const a=n.output;let i;return a&&(a.type==="text"||a.type==="error-text"||a.type==="json"||a.type==="error-json"?i=a.value:a.type==="execution-denied"?i={denied:!0,reason:a.reason}:i=a),{type:"tool_call_response",id:(r=n.toolCallId)!=null?r:null,response:i}}default:return{type:String(n.type)}}})};if(t.role==="tool")return{role:"tool",parts:t.content.map(n=>{var o;if(n.type==="tool-result"){const r=n.output;let a;return r&&(r.type==="text"||r.type==="error-text"||r.type==="json"||r.type==="error-json"?a=r.value:r.type==="execution-denied"?a={denied:!0,reason:r.reason}:a=r),{type:"tool_call_response",id:(o=n.toolCallId)!=null?o:null,response:a}}return{type:String(n.type)}})}}}function N({text:t,reasoning:e,toolCalls:n,files:o,finishReason:r}){const a=[];if(e)for(const i of e)"text"in i&&i.text&&a.push({type:"reasoning",content:i.text});if(t!=null&&t.length>0&&a.push({type:"text",content:t}),n)for(const i of n)a.push({type:"tool_call",id:i.toolCallId,name:i.toolName,arguments:i.input});if(o)for(const i of o)a.push({type:"blob",modality:_(i.mediaType),mime_type:i.mediaType,content:i.base64});return[{role:"assistant",parts:a,finish_reason:q(r)}]}function E({objectText:t,finishReason:e}){return[{role:"assistant",parts:[{type:"text",content:t}],finish_reason:q(e)}]}function q(t){var e;return(e={stop:"stop",length:"length","content-filter":"content_filter","tool-calls":"tool_call",error:"error",other:"stop",unknown:"stop"}[t])!=null?e:t}function h(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:l.SpanStatusCode.ERROR,message:e.message})):t.setStatus({code:l.SpanStatusCode.ERROR})}function w(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function I(t){if(!Array.isArray(t))return t;const e=new Set(t.filter(w).map(o=>typeof o));if(e.size!==1)return;const[n]=e;return n==="string"?t.filter(o=>typeof o=="string"):n==="number"?t.filter(o=>typeof o=="number"):t.filter(o=>typeof o=="boolean")}function L(t){const e={};for(const[n,o]of Object.entries(t??{})){if(o==null)continue;const r=I(o);r!=null&&(e[n]=r)}return e}function J(t){return t?.isEnabled!==!1}function d(t,e){if(!J(t))return{};const n={};for(const[o,r]of Object.entries(e)){if(r==null)continue;if(typeof r=="object"&&"input"in r&&typeof r.input=="function"){if(t?.recordInputs===!1)continue;const i=r.input();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(t?.recordOutputs===!1)continue;const i=r.output();if(i!=null){const s=I(i);s!=null&&(n[o]=s)}continue}const a=I(r);a!=null&&(n[o]=a)}return n}var D={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function K(t){var e,n,o,r,a,i,s,p;return{...D,usage:(e=t.usage)!=null?e:!1,providerMetadata:(n=t.providerMetadata)!=null?n:!1,embedding:(o=t.embedding)!=null?o:!1,reranking:(r=t.reranking)!=null?r:!1,runtimeContext:(a=t.runtimeContext)!=null?a:!1,headers:(i=t.headers)!=null?i:!1,toolChoice:(s=t.toolChoice)!=null?s:!1,schema:(p=t.schema)!=null?p:!1}}function $(t){const e={};for(const[n,o]of Object.entries(t??{}))R(e,`ai.settings.context.${n}`,o);return e}function R(t,e,n){if(n!=null){if(Array.isArray(n)||typeof n!="object"){t[e]=n;return}for(const[o,r]of Object.entries(n))R(t,`${e}.${o}`,r)}}function x(t){return Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!=null).map(([e,n])=>[`ai.request.headers.${e}`,n]))}function b(t){var e,n,o;return{"ai.usage.inputTokenDetails.noCacheTokens":(e=t.inputTokenDetails)==null?void 0:e.noCacheTokens,"ai.usage.outputTokenDetails.textTokens":(n=t.outputTokenDetails)==null?void 0:n.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(o=t.outputTokenDetails)==null?void 0:o.reasoningTokens}}function m(t,e,n){const o={};for(const[r,a]of Object.entries(n))!e[r]||a==null||Object.assign(o,d(t,a));return o}function C(t){return t==null?void 0:t/1e3}function W(t){var e;return{"gen_ai.client.operation.duration":C(t.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":C(t.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":C((e=t.timeBetweenOutputChunksMs)==null?void 0:e.avg)}}var z=class{constructor(t={}){this.callStates=new Map;var e;this.tracer=(e=t.tracer)!=null?e:l.trace.getTracer("gen_ai"),this.supplementalAttributes=K(t),this.enrichSpan=t.enrichSpan}getCallState(t){return this.callStates.get(t)}cleanupCallState(t){this.callStates.delete(t)}getSpanAttributes({attributes:t,spanType:e,operationId:n,callId:o,runtimeContext:r}){var a;let i;try{i=(a=this.enrichSpan)==null?void 0:a.call(this,{spanType:e,operationId:n,callId:o,runtimeContext:r})}catch{i=void 0}return{...L(i),...t}}executeTool({callId:t,toolCallId:e,execute:n}){var o;const r=(o=this.getCallState(t))==null?void 0:o.toolSpans.get(e);return r==null?n():l.context.with(r.context,n)}executeLanguageModelCall({callId:t,execute:e}){var n;const o=this.getCallState(t),r=(n=o?.inferenceContext)!=null?n:o?.stepContext;return r==null?e():l.context.with(r,e)}onStart(t){if(t.operationId==="ai.embed"||t.operationId==="ai.embedMany"){this.onEmbedOperationStart(t);return}if(t.operationId==="ai.rerank"){this.onRerankOperationStart(t);return}if(t.operationId==="ai.generateObject"||t.operationId==="ai.streamObject"){this.onObjectOperationStart(t);return}this.onGenerateStart(t)}onGenerateStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,stopSequences:t.stopSequences,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=t.runtimeContext,s=m(n,this.supplementalAttributes,{runtimeContext:$(i),headers:x(t.headers)}),p=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.stop_sequences":t.stopSequences,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.instructions?{input:()=>JSON.stringify(O(t.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:void 0,messages:t.messages}))},...s}),c=`${a} ${t.modelId}`,g=this.tracer.startSpan(c,{attributes:this.getSpanAttributes({attributes:p,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:i}),kind:l.SpanKind.INTERNAL}),u=l.trace.setSpan(l.context.active(),g);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:g,rootContext:u,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:i,baseSupplementalAttributes:s})}onObjectOperationStart(t){var e;const n={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},o={maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,topK:t.topK,presencePenalty:t.presencePenalty,frequencyPenalty:t.frequencyPenalty,seed:t.seed,maxRetries:t.maxRetries},r=S(t.provider),a=A(t.operationId),i=m(n,this.supplementalAttributes,{headers:x(t.headers)}),s=d(n,{"gen_ai.operation.name":a,"gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.agent.name":n.functionId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":t.frequencyPenalty,"gen_ai.request.max_tokens":t.maxOutputTokens,"gen_ai.request.presence_penalty":t.presencePenalty,"gen_ai.request.temperature":(e=t.temperature)!=null?e:void 0,"gen_ai.request.top_k":t.topK,"gen_ai.request.top_p":t.topP,"gen_ai.request.seed":t.seed,"gen_ai.system_instructions":t.system?{input:()=>JSON.stringify(O(t.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(k({prompt:t.prompt,messages:t.messages}))},...i,...m(n,this.supplementalAttributes,{schema:{"ai.schema":t.schema?{input:()=>JSON.stringify(t.schema)}:void 0,"ai.schema.name":t.schemaName,"ai.schema.description":t.schemaDescription,"ai.settings.output":t.output}})}),p=`${a} ${t.modelId}`,c=this.tracer.startSpan(p,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.INTERNAL}),g=l.trace.setSpan(l.context.active(),c);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:c,rootContext:g,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:o,provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:i})}onObjectStepStart(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan||!n.rootContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.output.type":"json","gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>t.promptMessages?JSON.stringify(v(t.promptMessages)):void 0},...n.baseSupplementalAttributes}),i=`chat ${t.modelId}`;n.inferenceSpan=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.rootContext),n.inferenceContext=l.trace.setSpan(n.rootContext,n.inferenceSpan)}onObjectStepEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.inferenceSpan)return;const{telemetry:o}=n;n.inferenceSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.response.id,"gen_ai.response.model":t.response.modelId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>{try{return JSON.stringify(E({objectText:t.objectText,finishReason:t.finishReason}))}catch{return t.objectText}}},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.inferenceSpan.end(),n.inferenceSpan=void 0,n.inferenceContext=void 0}onEmbedOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=t.value,a=t.operationId==="ai.embedMany",i=d(e,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>r.map(g=>JSON.stringify(g))}}:{"ai.value":{input:()=>JSON.stringify(r)}}})}),s=`embeddings ${t.modelId}`,p=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),c=l.trace.setSpan(l.context.active(),p);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:p,rootContext:c,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onStepStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e;e.runtimeContext=t.runtimeContext;const o=d(n,{"gen_ai.operation.name":"agent_step",...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{toolChoice:{"ai.prompt.toolChoice":{input:()=>t.stepToolChoice!=null?JSON.stringify(t.stepToolChoice):void 0}}})});e.stepSpan=this.tracer.startSpan(`step ${t.steps.length+1}`,{attributes:this.getSpanAttributes({attributes:o,spanType:"step",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.rootContext),e.stepContext=l.trace.setSpan(e.rootContext,e.stepSpan)}onLanguageModelCallStart(t){var e;const n=this.getCallState(t.callId);if(!n?.stepContext)return;const{telemetry:o}=n,r=S(t.provider),a=d(o,{"gen_ai.operation.name":"chat","gen_ai.provider.name":r,"gen_ai.request.model":t.modelId,"gen_ai.request.frequency_penalty":n.settings.frequencyPenalty,"gen_ai.request.max_tokens":n.settings.maxOutputTokens,"gen_ai.request.presence_penalty":n.settings.presencePenalty,"gen_ai.request.stop_sequences":n.settings.stopSequences,"gen_ai.request.temperature":(e=n.settings.temperature)!=null?e:void 0,"gen_ai.request.top_k":n.settings.topK,"gen_ai.request.top_p":n.settings.topP,"gen_ai.input.messages":{input:()=>{const i=k({prompt:void 0,messages:t.messages});return i.length>0?JSON.stringify(i):void 0}},"gen_ai.tool.definitions":{input:()=>t.tools?JSON.stringify(t.tools):void 0}});n.inferenceSpan=this.tracer.startSpan(`chat ${t.modelId}`,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:l.SpanKind.CLIENT},n.stepContext),n.inferenceContext=l.trace.setSpan(n.stepContext,n.inferenceSpan)}onLanguageModelCallEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.inferenceSpan)return;const{telemetry:r}=o;o.inferenceSpan.setAttributes(d(r,{...W(t.performance),"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.response.id":t.responseId,"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>JSON.stringify(N({text:t.content.filter(a=>a.type==="text").map(a=>a.text).join("")||void 0,reasoning:t.content.filter(a=>a.type==="reasoning"),toolCalls:t.content.filter(a=>a.type==="tool-call"),files:t.content.filter(a=>a.type==="file").map(a=>a.file),finishReason:t.finishReason}))},...m(r,this.supplementalAttributes,{usage:b(t.usage)})})),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0}onToolExecutionStart(t){const e=this.getCallState(t.callId);if(!e?.stepContext)return;const{telemetry:n}=e,{toolCall:o}=t,r=d(n,{"gen_ai.operation.name":"execute_tool","gen_ai.tool.name":o.toolName,"gen_ai.tool.call.id":o.toolCallId,"gen_ai.tool.type":"function","gen_ai.tool.call.arguments":{input:()=>JSON.stringify(o.input)}}),a=`execute_tool ${o.toolName}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"tool",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.INTERNAL},e.stepContext),s=l.trace.setSpan(e.stepContext,i);e.toolSpans.set(o.toolCallId,{span:i,context:s})}onToolExecutionEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.toolSpans.get(t.toolCall.toolCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e,{toolOutput:a}=t;if(o.setAttributes(d(r,{"gen_ai.execute_tool.duration":C(t.toolExecutionMs)})),a.type==="tool-result")try{o.setAttributes(d(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else h(o,a.error);o.end(),e.toolSpans.delete(t.toolCall.toolCallId)}onStepEnd(t){const e=this.getCallState(t.callId);if(!e?.stepSpan)return;const{telemetry:n}=e;e.stepSpan.setAttributes(m(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})),e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0}onStepFinish(t){this.onStepEnd(t)}onEnd(t){const e=this.getCallState(t.callId);if(e?.rootSpan){if(e.operationId==="ai.embed"||e.operationId==="ai.embedMany"){this.onEmbedOperationEnd(t);return}if(e.operationId==="ai.rerank"){this.onRerankOperationEnd(t);return}if(e.operationId==="ai.generateObject"||e.operationId==="ai.streamObject"){this.onObjectOperationEnd(t);return}this.onGenerateEnd(t)}}onGenerateEnd(t){var e,n;const o=this.getCallState(t.callId);if(!o?.rootSpan)return;const{telemetry:r}=o;o.rootSpan.setAttributes(d(r,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.usage.cache_creation.input_tokens":(n=t.usage.inputTokenDetails)==null?void 0:n.cacheWriteTokens,"gen_ai.output.messages":{output:()=>{var a;return JSON.stringify(N({text:(a=t.text)!=null?a:void 0,reasoning:t.finalStep.reasoning,toolCalls:t.toolCalls,files:t.files,finishReason:t.finishReason}))}},...m(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.finalStep.providerMetadata?JSON.stringify(t.finalStep.providerMetadata):void 0},usage:b(t.usage)})})),o.rootSpan.end(),this.cleanupCallState(t.callId)}onObjectOperationEnd(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan)return;const{telemetry:o}=n;n.rootSpan.setAttributes(d(o,{"gen_ai.response.finish_reasons":[t.finishReason],"gen_ai.usage.input_tokens":t.usage.inputTokens,"gen_ai.usage.output_tokens":t.usage.outputTokens,"gen_ai.usage.cache_read.input_tokens":(e=t.usage.inputTokenDetails)==null?void 0:e.cacheReadTokens,"gen_ai.output.messages":{output:()=>t.object!=null?JSON.stringify(E({objectText:JSON.stringify(t.object),finishReason:t.finishReason})):void 0},...m(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:b(t.usage)})})),n.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedOperationEnd(t){const e=this.getCallState(t.callId);if(!e?.rootSpan)return;const{telemetry:n}=e,o=e.operationId==="ai.embedMany";e.rootSpan.setAttributes(d(n,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(n,this.supplementalAttributes,{embedding:o?{"ai.embeddings":{output:()=>t.embedding.map(r=>JSON.stringify(r))}}:{"ai.embedding":{output:()=>JSON.stringify(t.embedding)}}})})),e.rootSpan.end(),this.cleanupCallState(t.callId)}onEmbedStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>t.values.map(p=>JSON.stringify(p))}}})}),a=`embeddings ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.embedSpans.set(t.embedCallId,{span:i,context:s})}onEmbedEnd(t){const e=this.getCallState(t.callId);if(!e)return;const n=e.embedSpans.get(t.embedCallId);if(!n)return;const{span:o}=n,{telemetry:r}=e;o.setAttributes(d(r,{"gen_ai.usage.input_tokens":t.usage.tokens,...m(r,this.supplementalAttributes,{embedding:{"ai.embeddings":{output:()=>t.embeddings.map(a=>JSON.stringify(a))}}})})),o.end(),e.embedSpans.delete(t.embedCallId)}onRerankOperationStart(t){const e={recordInputs:t.recordInputs,recordOutputs:t.recordOutputs,functionId:t.functionId},n=S(t.provider),o=m(e,this.supplementalAttributes,{headers:x(t.headers)}),r=d(e,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...m(e,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${t.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:l.SpanKind.CLIENT}),s=l.trace.setSpan(l.context.active(),i);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:i,rootContext:s,stepSpan:void 0,stepContext:void 0,inferenceSpan:void 0,inferenceContext:void 0,embedSpans:new Map,rerankSpan:void 0,toolSpans:new Map,settings:{maxRetries:t.maxRetries},provider:t.provider,modelId:t.modelId,runtimeContext:void 0,baseSupplementalAttributes:o})}onRerankOperationEnd(t){const e=this.getCallState(t.callId);e?.rootSpan&&(e.rootSpan.end(),this.cleanupCallState(t.callId))}onRerankStart(t){const e=this.getCallState(t.callId);if(!e?.rootSpan||!e.rootContext)return;const{telemetry:n}=e,o=S(e.provider),r=d(n,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...m(n,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(p=>JSON.stringify(p))}}})}),a=`rerank ${e.modelId}`,i=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:l.SpanKind.CLIENT},e.rootContext),s=l.trace.setSpan(e.rootContext,i);e.rerankSpan={span:i,context:s}}onRerankEnd(t){const e=this.getCallState(t.callId);if(!e?.rerankSpan)return;const{span:n}=e.rerankSpan,{telemetry:o}=e;n.setAttributes(m(o,this.supplementalAttributes,{reranking:{"ai.ranking.type":t.documentsType,"ai.ranking":{output:()=>t.ranking.map(r=>JSON.stringify(r))}}})),n.end(),e.rerankSpan=void 0}onAbort(t){const e=this.getCallState(t.callId);if(e?.rootSpan){for(const{span:n}of e.toolSpans.values())n.end();e.toolSpans.clear(),e.inferenceSpan&&(e.inferenceSpan.end(),e.inferenceSpan=void 0,e.inferenceContext=void 0),e.stepSpan&&(e.stepSpan.end(),e.stepSpan=void 0,e.stepContext=void 0);for(const{span:n}of e.embedSpans.values())n.end();e.embedSpans.clear(),e.rerankSpan&&(e.rerankSpan.span.end(),e.rerankSpan=void 0),e.rootSpan.end(),this.cleanupCallState(t.callId)}}onError(t){var e;const n=t;if(!n?.callId)return;const o=this.getCallState(n.callId);if(!o?.rootSpan)return;const r=(e=n.error)!=null?e:t;for(const{span:a}of o.toolSpans.values())h(a,r),a.end();o.toolSpans.clear(),o.inferenceSpan&&(h(o.inferenceSpan,r),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0),o.stepSpan&&(h(o.stepSpan,r),o.stepSpan.end(),o.stepSpan=void 0,o.stepContext=void 0);for(const{span:a}of o.embedSpans.values())h(a,r),a.end();o.embedSpans.clear(),o.rerankSpan&&(h(o.rerankSpan.span,r),o.rerankSpan.span.end(),o.rerankSpan=void 0),h(o.rootSpan,r),o.rootSpan.end(),this.cleanupCallState(n.callId)}};function U(t){return y.pruneMessages({messages:t,emptyMessages:"remove",reasoning:"none",toolCalls:`before-last-${l.TOOL_CALL_MESSAGES_TO_KEEP}-messages`})}function B(t){return typeof t=="object"&&t!==null&&"role"in t&&"content"in t}function G(t){return Array.isArray(t)&&t.every(B)}function F(t,{conversationId:e,getModel:n}){let o=0;const r=()=>{const a=n?.();return a?{model_provider:a.provider,model_id:a.modelId}:{}};return{onStepStart:()=>{o+=1},onToolExecutionStart:a=>{t("com.redocly.aiChat.toolCallStarted",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,...r()}])},onToolExecutionEnd:a=>{const i=a.toolOutput.type==="tool-error";t("com.redocly.aiChat.toolCallFinished",[{conversation_id:e,...l.createResource("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,success:!i,duration_ms:a.toolExecutionMs,...r(),...i&&{error:a.toolOutput.error instanceof Error?a.toolOutput.error.message:String(a.toolOutput.error)}}])},onStart:a=>{o=0,t("com.redocly.aiChat.conversationStarted",[{...l.createResource("conversation",e,"ai"),model_provider:"provider"in a?a.provider:"unknown",model_id:"modelId"in a?a.modelId:"unknown"}])},onEnd:a=>{if(!("steps"in a))return;const i=a.usage;t("com.redocly.aiChat.conversationFinished",[{...l.createResource("conversation",e,"ai"),model_provider:a.model.provider,model_id:a.model.modelId,success:!0,step_count:a.steps.length,finish_reason:a.finishReason,input_tokens:i.inputTokens,output_tokens:i.outputTokens,total_tokens:i.totalTokens}])}}}function V(t,e){const n=()=>l.trace.getSpan(l.context.active())?l.context.active():e;return{startSpan:(o,r,a)=>t.startSpan(o,r,a??e),startActiveSpan:((o,r,a,i)=>{if(typeof r=="function")return t.startActiveSpan(o,{},n(),r);if(typeof a=="function")return t.startActiveSpan(o,r,n(),a);if(i)return t.startActiveSpan(o,r,a,i);throw new Error("withParentContext: invalid startActiveSpan invocation")})}}class H{model;tools;toolLoopAgent;maxSteps;context=[];systemInstructions=j.getSystemInstructions();getActiveStateMessage;constructor(e){const{activeConversationId:n,onFinish:o,onStepFinish:r,tools:a}=e;this.maxSteps=e.maxSteps??l.DEFAULT_MAX_STEPS,this.getActiveStateMessage=e.getActiveStateMessage,this.model=this.createModel(e.model);const i=({stepNumber:c,messages:g})=>{const u=[],f=this.buildActiveStateMessage();return f&&u.push({role:"user",content:f}),c===this.maxSteps-1&&u.push({role:"user",content:T.LAST_STEP_PROMPT}),u.length===0?void 0:{messages:[...g,...u]}},s=c=>{const g=c.messages?this.prepareMessages(c.messages):void 0,u=c.prompt?this.preparePrompt(c.prompt):void 0;return{...c,model:this.model,messages:g,prompt:u,instructions:[...this.systemInstructions,...this.context],tools:this.tools??c.tools}},p=new z({...e.parentCtx&&{tracer:V(l.trace.getTracer("ai"),e.parentCtx)}});this.toolLoopAgent=new y.ToolLoopAgent({model:this.model,tools:a,stopWhen:y.isStepCount(this.maxSteps),onStepFinish:r,onFinish:o,maxOutputTokens:e.maxOutputTokens,maxRetries:e.maxRetries??l.DEFAULT_MAX_RETRIES,prepareStep:i,prepareCall:s,telemetry:{isEnabled:!0,recordInputs:!0,recordOutputs:!0,functionId:"replay-ai-chat",integrations:[p,F(e.sendEvent,{conversationId:n,getModel:()=>({provider:this.model.provider,modelId:this.model.modelId})})]}})}createModel(e){return y.createModel(e)}setModel(e){this.model=this.createModel(e)}getAgent(){return this.toolLoopAgent}addContext(e){this.context.push(...e)}registerTools(e){this.tools=e}async generateTitle(e,n){return y.streamText({model:this.model,system:T.CONVERSATION_TITLE_PROMPT,prompt:e,temperature:0,abortSignal:n}).text}buildActiveStateMessage(){if(!this.getActiveStateMessage)return null;try{return this.getActiveStateMessage()||null}catch(e){return console.error(e),null}}prepareMessages(e){return U(e)}preparePrompt(e){return G(e)?this.prepareMessages(e):e}}exports.AgentLoop=H;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { v as n, R as d, A as i } from "./replay-index-4TEahAPK.js";
|
|
2
2
|
function A() {
|
|
3
3
|
return `aichat_${n()}`;
|
|
4
4
|
}
|
|
@@ -92,8 +92,8 @@ function C(e) {
|
|
|
92
92
|
}
|
|
93
93
|
export {
|
|
94
94
|
M as a,
|
|
95
|
-
|
|
95
|
+
g as b,
|
|
96
96
|
h as c,
|
|
97
|
-
|
|
97
|
+
v as d,
|
|
98
98
|
A as g
|
|
99
99
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const i=require("./replay-index-
|
|
1
|
+
"use strict";const i=require("./replay-index-Nz5obVS5.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 {
|
|
1
|
+
import { f as _, s as d, i as a, t as e, a as i, u as n } from "./replay-indexes-B3PJtgeh.js";
|
|
2
2
|
const s = _`(cast(round(unixepoch('subsec') * 1000) as integer))`, l = d(
|
|
3
3
|
"ai_chats",
|
|
4
4
|
{
|