@redocly/replay 0.27.0-next.7 → 0.27.0-next.8
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-Dub7iVgM.js → replay-AiChatProvider-DHIxHTKX.js} +6 -6
- package/dist/{replay-AiChatProvider-e4PWUCRp.js → replay-AiChatProvider-O8HHQobN.js} +1 -1
- package/dist/{replay-AiChatSqliteDBStorage-DbxNU-ot.js → replay-AiChatSqliteDBStorage-DNMrzkJg.js} +1 -1
- package/dist/{replay-AiChatSqliteDBStorage-CpjwxLnF.js → replay-AiChatSqliteDBStorage-DjUq9VX3.js} +1 -1
- package/dist/{replay-AiPanel-DuRA2zAt.js → replay-AiPanel-CR815YqV.js} +3 -3
- package/dist/{replay-AiPanel-B_zDmo55.js → replay-AiPanel-CfYBCkrN.js} +1 -1
- package/dist/{replay-SqliteDBStorage-CafBNNLB.js → replay-SqliteDBStorage-B3oYWXem.js} +1 -1
- package/dist/{replay-SqliteDBStorage-BrNleq7S.js → replay-SqliteDBStorage-CC9kLioX.js} +1 -1
- package/dist/{replay-agent-loop-CV0s4022.js → replay-agent-loop-CCYOzyHo.js} +3 -3
- package/dist/{replay-agent-loop-CzV79Gr1.js → replay-agent-loop-CTq5eJ4u.js} +1 -1
- package/dist/{replay-ai-chat-mappers-BWeZN6p_.js → replay-ai-chat-mappers-B_wovMvG.js} +1 -1
- package/dist/{replay-ai-chat-mappers-BNsR30dS.js → replay-ai-chat-mappers-C8y5UhCq.js} +1 -1
- package/dist/{replay-create-model-CEDEaJC8.js → replay-create-model-C5yvtnXA.js} +2 -2
- package/dist/{replay-create-model-CmRk68RD.js → replay-create-model-CBCmuEKC.js} +2 -2
- package/dist/{replay-db-BfSnfWcb.js → replay-db-CCBQadnT.js} +1 -1
- package/dist/{replay-db-CM8OLcFK.js → replay-db-DfOjLqsq.js} +1 -1
- package/dist/{replay-external-resolver-bdSEZsNk.js → replay-external-resolver-B6tpqUZt.js} +1 -1
- package/dist/{replay-external-resolver-G86hjAvS.js → replay-external-resolver-BRouROm6.js} +2 -2
- package/dist/{replay-index-DYtNY0OY.js → replay-index-B_OHqSlS.js} +5 -5
- package/dist/{replay-index-D58Mg6_y.js → replay-index-Bzttek8l.js} +1 -1
- package/dist/{replay-index-Cd9LaUVx.js → replay-index-BzzBKjHm.js} +12191 -12184
- package/dist/{replay-index-Bsag-eKM.js → replay-index-Cpkh9r0X.js} +1 -1
- package/dist/{replay-index-BmotNqNI.js → replay-index-Dfnqt_IZ.js} +977 -977
- package/dist/{replay-index-C_eJVbPZ.js → replay-index-Xq6K7XSm.js} +1 -1
- package/dist/{replay-lint-YfaLafO6.js → replay-lint-DlDmPTBV.js} +6950 -6653
- package/dist/{replay-lint-graphql-BRrk1UK5.js → replay-lint-graphql-BQJ00lU4.js} +1 -1
- package/dist/{replay-lint-graphql-GtbZklco.js → replay-lint-graphql-DHOq8lRT.js} +1 -1
- package/dist/replay-lint-gtuMJgII.js +184 -0
- package/dist/{replay-resolve-Bza6lozO.js → replay-resolve-DqFS69S_.js} +1 -1
- package/dist/{replay-resolve-Rb3XjiUd.js → replay-resolve-DsgcWnjC.js} +1 -1
- package/dist/{replay-respect-run-Pkoy4Q3P.js → replay-respect-run-7Cwe1_ri.js} +23 -23
- package/dist/{replay-respect-run-BB0VXCz-.js → replay-respect-run-D1zyh-5j.js} +297 -295
- package/dist/{replay-tauri-path-B8tT4cGY.js → replay-tauri-path-BAY3g5sW.js} +2 -2
- package/dist/{replay-tauri-path-yOFqWleH.js → replay-tauri-path-CaVeI3a-.js} +1 -1
- package/dist/{replay-useAiChatQueries-B7ZcWDmG.js → replay-useAiChatQueries-CxZNLVje.js} +3 -3
- package/dist/{replay-useAiChatQueries-1fqZwVTj.js → replay-useAiChatQueries-D99tAUpY.js} +1 -1
- package/dist/{replay-validate-key-C8-nF61w.js → replay-validate-key-Cv0mvYDS.js} +1 -1
- package/dist/{replay-validate-key-qJOuAQJK.js → replay-validate-key-Di8MCBz7.js} +2 -2
- package/dist/replay.cjs +1 -1
- package/dist/replay.js +1 -1
- package/package.json +4 -4
- package/dist/replay-lint-CxwKILeF.js +0 -184
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { jsx as te } from "react/jsx-runtime";
|
|
2
2
|
import { useRef as R, useCallback as f, useSyncExternalStore as re, useEffect as b, useMemo as w, useState as z } from "react";
|
|
3
|
-
import { a as S, A as ce, g as Re, I as xe, T as $e, b as x, c as Pe, d as De, u as Te, e as We, f as Be, h as Oe, i as Ue, j as Ae, k as se, l as ue, m as ye, n as Fe, o as Le, p as Se, t as ge, q as je, R as ne, r as Ne, s as ae, v as qe, w as Ke } from "./replay-index-
|
|
4
|
-
import { A as Qe, D as Ve, l as Ge } from "./replay-create-model-
|
|
5
|
-
import { AgentLoop as He } from "./replay-agent-loop-
|
|
6
|
-
import { s as ze } from "./replay-db-
|
|
7
|
-
import { r as Ye, g as Je, a as Xe, o as Ze, s as et, w as tt, m as nt, b as st, u as rt, c as ot, d as at, e as it, f as lt, h as ct, i as ut, A as dt, j as ht, k as pt } from "./replay-useAiChatQueries-
|
|
3
|
+
import { a as S, A as ce, g as Re, I as xe, T as $e, b as x, c as Pe, d as De, u as Te, e as We, f as Be, h as Oe, i as Ue, j as Ae, k as se, l as ue, m as ye, n as Fe, o as Le, p as Se, t as ge, q as je, R as ne, r as Ne, s as ae, v as qe, w as Ke } from "./replay-index-BzzBKjHm.js";
|
|
4
|
+
import { A as Qe, D as Ve, l as Ge } from "./replay-create-model-C5yvtnXA.js";
|
|
5
|
+
import { AgentLoop as He } from "./replay-agent-loop-CCYOzyHo.js";
|
|
6
|
+
import { s as ze } from "./replay-db-DfOjLqsq.js";
|
|
7
|
+
import { r as Ye, g as Je, a as Xe, o as Ze, s as et, w as tt, m as nt, b as st, u as rt, c as ot, d as at, e as it, f as lt, h as ct, i as ut, A as dt, j as ht, k as pt } from "./replay-useAiChatQueries-CxZNLVje.js";
|
|
8
8
|
import { useQueryClient as de, useMutation as he } from "@tanstack/react-query";
|
|
9
|
-
import { b as be, g as me } from "./replay-ai-chat-mappers-
|
|
9
|
+
import { b as be, g as me } from "./replay-ai-chat-mappers-C8y5UhCq.js";
|
|
10
10
|
class ft {
|
|
11
11
|
handlers = /* @__PURE__ */ new Map();
|
|
12
12
|
middlewares;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),a=require("./replay-index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),a=require("./replay-index-Dfnqt_IZ.js"),te=require("./replay-create-model-CBCmuEKC.js"),pe=require("./replay-agent-loop-CTq5eJ4u.js"),ge=require("./replay-db-CCBQadnT.js"),m=require("./replay-useAiChatQueries-D99tAUpY.js"),F=require("@tanstack/react-query"),Z=require("./replay-ai-chat-mappers-B_wovMvG.js");class Ce{handlers=new Map;middlewares;constructor(t){this.middlewares=t?.middlewares??[]}register(t){this.handlers.set(t.name,t)}getToolSet(){const t={};for(const[n,s]of this.handlers)t[n]=this.buildTool(s);return t}buildTool(t){return{...t.definition,execute:this.wrapExecutor(t)}}wrapExecutor(t){const n=(o,r)=>({isError:!0,error:{message:o,details:r}}),s=this.applyMiddlewares(t.name,t.execute);return(o,r)=>{if(r.abortSignal?.aborted)return n("Tool execution was aborted.");try{const l=s(o,r);return typeof l=="object"&&l!==null&&"then"in l?l.then(c=>c,c=>n(c instanceof Error?c.message:"Unknown tool execution error")):l}catch(l){return n(l instanceof Error?l.message:"Unknown tool execution error")}}}applyMiddlewares(t,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((s,o)=>o(t,s),n)}}function ue(){const e=F.useQueryClient();return F.useMutation({async mutationFn(t){const n=Z.buildPersistableUiChat(t);await a.AiChatServiceFactory.getInstance().upsert(n)},onSuccess(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(t){console.error("Failed to upsert ai chat item:",t)}})}function me(e){const t=F.useQueryClient(),n=a.aiChatKeys.detailTitle(e??"");return F.useMutation({mutationKey:n,async mutationFn(s){if(t.isMutating({mutationKey:n,exact:!0})>1)return;const o=Z.buildPersistableUiChat(s);await a.AiChatServiceFactory.getInstance().upsert(o)},onSuccess(){t.invalidateQueries({queryKey:a.aiChatKeys.all()})},onError(s){console.error("Failed to upsert ai chat item:",s)}})}function ve(){const e=F.useQueryClient();return F.useMutation({async mutationFn(t){await a.AiChatServiceFactory.getInstance().remove(t)},onMutate:async t=>{await e.cancelQueries({queryKey:a.aiChatKeys.all()});const n=e.getQueryData(a.aiChatKeys.all());n&&e.setQueryData(a.aiChatKeys.all(),n.filter(s=>s.id!==t)),e.setQueryData(a.aiChatKeys.detail(t),null),e.setQueriesData({queryKey:a.aiChatKeys.infiniteHistories()},s=>s&&{...s,pages:s.pages.map(o=>({...o,items:o.items.filter(r=>r.id!==t)}))})},onError(t){console.error("Failed to remove ai chat:",t)},onSettled(){e.invalidateQueries({queryKey:a.aiChatKeys.all()})}})}var ee,ae;function we(){if(ae)return ee;ae=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let s,o=0;return function(...l){clearTimeout(s);const c=Date.now(),u=c-o,h=n-u;h<=0?(o=c,t.apply(this,l)):s=setTimeout(()=>{o=Date.now(),t.apply(this,l)},h)}}return ee=e,ee}var Ie=we();const Te=a.getDefaultExportFromCjs(Ie);var de=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},f=(e,t,n)=>(de(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},M=(e,t,n,s)=>(de(e,t,"write to private field"),t.set(e,n),n);function ye(e,t){return t!=null?Te(e,t):e}var w,Y,J,j,Q,V,B,ne,se,be=class{constructor(e=[]){b(this,w,void 0),b(this,Y,"ready"),b(this,J,void 0),b(this,j,new Set),b(this,Q,new Set),b(this,V,new Set),this.pushMessage=t=>{M(this,w,f(this,w).concat(t)),f(this,B).call(this)},this.popMessage=()=>{M(this,w,f(this,w).slice(0,-1)),f(this,B).call(this)},this.replaceMessage=(t,n)=>{M(this,w,[...f(this,w).slice(0,t),this.snapshot(n),...f(this,w).slice(t+1)]),f(this,B).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const s=n?ye(t,n):t;return f(this,j).add(s),()=>{f(this,j).delete(s)}},this["~registerStatusCallback"]=t=>(f(this,Q).add(t),()=>{f(this,Q).delete(t)}),this["~registerErrorCallback"]=t=>(f(this,V).add(t),()=>{f(this,V).delete(t)}),b(this,B,()=>{f(this,j).forEach(t=>t())}),b(this,ne,()=>{f(this,Q).forEach(t=>t())}),b(this,se,()=>{f(this,V).forEach(t=>t())}),M(this,w,e)}get status(){return f(this,Y)}set status(e){M(this,Y,e),f(this,ne).call(this)}get error(){return f(this,J)}set error(e){M(this,J,e),f(this,se).call(this)}get messages(){return f(this,w)}set messages(e){M(this,w,[...e]),f(this,B).call(this)}};w=new WeakMap;Y=new WeakMap;J=new WeakMap;j=new WeakMap;Q=new WeakMap;V=new WeakMap;B=new WeakMap;ne=new WeakMap;se=new WeakMap;var L,ie=class extends te.AbstractChat{constructor({messages:e,...t}){const n=new be(e);super({...t,state:n}),b(this,L,void 0),this["~registerMessagesCallback"]=(s,o)=>f(this,L)["~registerMessagesCallback"](s,o),this["~registerStatusCallback"]=s=>f(this,L)["~registerStatusCallback"](s),this["~registerErrorCallback"]=s=>f(this,L)["~registerErrorCallback"](s),M(this,L,n)}};L=new WeakMap;function Se({experimental_throttle:e,resume:t=!1,...n}={}){const s=i.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const o={...n,onToolCall:d=>{var g,p;return(p=(g=s.current).onToolCall)==null?void 0:p.call(g,d)},onData:d=>{var g,p;return(p=(g=s.current).onData)==null?void 0:p.call(g,d)},onFinish:d=>{var g,p;return(p=(g=s.current).onFinish)==null?void 0:p.call(g,d)},onError:d=>{var g,p;return(p=(g=s.current).onError)==null?void 0:p.call(g,d)},sendAutomaticallyWhen:d=>{var g,p,R;return(R=(p=(g=s.current).sendAutomaticallyWhen)==null?void 0:p.call(g,d))!=null?R:!1}},r=i.useRef("chat"in n?n.chat:new ie(o));("chat"in n&&n.chat!==r.current||"id"in n&&n.id!=null&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new ie(o));const c=i.useCallback(d=>r.current["~registerMessagesCallback"](d,e),[e,r.current.id]),u=i.useSyncExternalStore(c,()=>r.current.messages,()=>r.current.messages),h=i.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),I=i.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),T=i.useCallback(d=>{typeof d=="function"&&(d=d(r.current.messages)),r.current.messages=d},[r]);return i.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:u,setMessages:T,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:I,resumeStream:r.current.resumeStream,status:h,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput,addToolApprovalResponse:r.current.addToolApprovalResponse}}const Ae=20;function ke(e){if(e.length===0)return"No OpenAPI specs loaded.";const t=e.slice(0,Ae),n=t.map(Ee),s=e.length-t.length;return s>0&&n.push(` …and ${s} more API(s) not shown.`),[`Loaded APIs (${e.length}):`,...n].join(`
|
|
2
2
|
`)}function Ee(e){return[` apiId="${e.apiId}"`,`title="${e.title}"`,e.version?`version="${e.version}"`:null,e.primaryServer?`server="${e.primaryServer}"`:null].filter(Boolean).join(" ")}const Me=30;function Re(e){if(e.length===0)return"No Arazzo collections loaded.";const t=[`Arazzo collections (${e.length}):`];let n=Me,s=0,o=0;for(const l of e){if(n<=0){s+=l.workflows.length,o++;continue}if(t.push(_e(l)),n--,l.workflows.length===0)t.push(" (no workflows)");else if(n>=2){t.push(` workflows (${l.workflows.length}):`),n--;for(const c of l.workflows)n>0?(t.push(` ${xe(c)}`),n--):s++}else s+=l.workflows.length}const r=[s>0?`${s} more workflow(s)`:null,o>0?`${o} more collection(s)`:null].filter(Boolean);return r.length>0&&t.push(` …and ${r.join(", plus ")} not shown.`),t.join(`
|
|
3
3
|
`)}function _e(e){const t=e.sourceApiIds.length>0?` apis=[${e.sourceApiIds.join(", ")}]`:"";return` collectionId="${e.collectionId}" title="${e.title}"${t}`}function xe(e){const t=`id="${e.workflowId}"`,n=e.summary?`label="${e.summary}"`:null,s=`[${e.stepCount} step${e.stepCount!==1?"s":""}]`;return[t,n,s].filter(Boolean).join(" ")}const Pe=20;function De(e){if(e.length===0)return"No environments configured.";const t=e.slice(0,Pe),n=t.map($e),s=e.length-t.length;return s>0&&n.push(` …and ${s} more environment(s) not shown.`),[`Environments (${e.length}); * marks the active environment:`,...n].join(`
|
|
4
4
|
`)}function $e(e){return[`${e.isActive?"*":" "} name="${e.name}"`,`inputs=${e.inputCount}`,`servers=${e.serverCount}`].join(" ")}const Oe=30;function We(e){if(e.length===0)return"No tabs are open.";const t=e.slice(0,Oe),n=t.map(Ue),s=e.length-t.length;return s>0&&n.push(` …and ${s} more tab(s) not shown.`),[`Open tabs (${e.length}), listed by tabIndex; * marks the active (focused) tab:`,...n].join(`
|
package/dist/{replay-AiChatSqliteDBStorage-DbxNU-ot.js → replay-AiChatSqliteDBStorage-DNMrzkJg.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "./replay-history.schema-5ce6X0R1.js";
|
|
2
2
|
import "./replay-step-context.schema-DBk4jufr.js";
|
|
3
3
|
import { a as h, b as r, c as n } from "./replay-ai-message-parts.schema-E9u9-nqr.js";
|
|
4
|
-
import { c, a as u, d as m } from "./replay-ai-chat-mappers-
|
|
4
|
+
import { c, a as u, d as m } from "./replay-ai-chat-mappers-C8y5UhCq.js";
|
|
5
5
|
import { a as l, e, b as y } from "./replay-indexes-CfsvVMi_.js";
|
|
6
6
|
const g = {
|
|
7
7
|
orderBy: [l(r.createdAt), l(r.indexWithinInsertBatch)],
|
package/dist/{replay-AiChatSqliteDBStorage-CpjwxLnF.js → replay-AiChatSqliteDBStorage-DjUq9VX3.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./replay-history.schema-miM3Etuf.js");require("./replay-step-context.schema-BuuXkAck.js");const i=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),h=require("./replay-ai-chat-mappers-B_wovMvG.js"),s=require("./replay-indexes-Dqjl8m6C.js"),c={orderBy:[s.asc(i.aiMessages.createdAt),s.asc(i.aiMessages.indexWithinInsertBatch)],with:{parts:{orderBy:[s.asc(i.aiMessageParts.index)]}}};class g{constructor(e){this.sqliteDB=e}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:c}})).map(h.convertAiChatRowToUiChat)}async findRecentChatsPage(e){await this.initialize();const a=e.limit+1,r=await this.db.query.aiChats.findMany({orderBy:(d,{desc:o})=>o(d.updatedAt),limit:a,offset:e.offset}),t=r.slice(0,e.limit),n=r.length>e.limit,w=e.offset+t.length;return{items:t.map(d=>{const o={...d,messages:[]};return h.convertAiChatRowToUiChat(o)}),hasMore:n,nextOffset:w}}async findOne(e){await this.initialize();const a=await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,e),with:{messages:c}});return a&&h.convertAiChatRowToUiChat(a)}async upsert(e){await this.initialize();const a=h.convertUiChatToAiChatRow(e);await this.db.query.aiChats.findFirst({where:s.eq(i.aiChats.id,a.id),columns:{id:!0}})?await this.db.update(i.aiChats).set(a).where(s.eq(i.aiChats.id,a.id)):await this.db.insert(i.aiChats).values(a);for(let t=0;t<e.messages.length;t++)await this.upsertMessageRowAndParts(e.id,t,e.messages[t])}async remove(e){await this.initialize(),await this.db.delete(i.aiChats).where(s.eq(i.aiChats.id,e))}async upsertMessageRowAndParts(e,a,r){const t=await this.db.query.aiMessages.findFirst({where:s.and(s.eq(i.aiMessages.aiChatId,e),s.eq(i.aiMessages.uiId,r.id))}),n=h.convertUiMessageToAiChatMessage(e,a,r,t?.id);t?await this.db.update(i.aiMessages).set({...n,indexWithinInsertBatch:t.indexWithinInsertBatch}).where(s.eq(i.aiMessages.id,t.id)):await this.db.insert(i.aiMessages).values(n),await this.db.delete(i.aiMessageParts).where(s.eq(i.aiMessageParts.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(i.aiMessageParts).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}exports.AiChatSqliteDBStorage=g;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { jsx as i, jsxs as h, Fragment as Ne } from "react/jsx-runtime";
|
|
2
2
|
import { useCallback as D, useMemo as A, useState as G, Fragment as mt, useRef as N, useEffect as H, useLayoutEffect as Fe, createContext as yt, useContext as xt } from "react";
|
|
3
3
|
import c, { css as X, keyframes as bt } from "styled-components";
|
|
4
|
-
import { G as je, T as te, H as Ce, J as wt, b as Ct, m as We, i as kt, j as Tt, K as It, L as ge, N as ve, O as M, P as be, Q as At, U as St, V as Ue, W as Lt, X as Pt, R as me, E as pe, Y as ke, Z as Ye, p as Ge, _ as we, $ as W, a0 as Et } from "./replay-index-
|
|
5
|
-
import { l as Rt, n as Ot, p as $t, q as Dt, T as zt, t as Mt, v as _t, x as qe, C as k, y as Vt, z as Ke, L as Bt, B as Q, D as Ht, E as Nt, F as Ft, G as jt, H as F } from "./replay-useAiChatQueries-
|
|
4
|
+
import { G as je, T as te, H as Ce, J as wt, b as Ct, m as We, i as kt, j as Tt, K as It, L as ge, N as ve, O as M, P as be, Q as At, U as St, V as Ue, W as Lt, X as Pt, R as me, E as pe, Y as ke, Z as Ye, p as Ge, _ as we, $ as W, a0 as Et } from "./replay-index-BzzBKjHm.js";
|
|
5
|
+
import { l as Rt, n as Ot, p as $t, q as Dt, T as zt, t as Mt, v as _t, x as qe, C as k, y as Vt, z as Ke, L as Bt, B as Q, D as Ht, E as Nt, F as Ft, G as jt, H as F } from "./replay-useAiChatQueries-CxZNLVje.js";
|
|
6
6
|
import { AI_SEARCH_MAX_MESSAGE_LENGTH as Wt, Button as B, SubtractIcon as Ut, AddIcon as Yt, CheckmarkFilledIcon as Gt, CloseFilledIcon as qt, CheckboxIcon as Kt, capitalize as re, ChevronDownIcon as Zt, ChevronRightIcon as Jt, SettingsCogIcon as Xt, Dropdown as Qt, DropdownMenu as en, DropdownMenuItem as Ze, CheckmarkIcon as tn, ClaudeIcon as nn, GeminiIcon as on, ChatGptIcon as rn, Tooltip as U, Typography as se, TrashCanIcon as an, AiStarsGradientIcon as sn, NewChatIcon as cn, RecentlyViewedIcon as ln, CloseIcon as dn, ArrowLeftIcon as un } from "@redocly/theme";
|
|
7
|
-
import { M as z } from "./replay-db-
|
|
7
|
+
import { M as z } from "./replay-db-DfOjLqsq.js";
|
|
8
8
|
import "@tanstack/react-query";
|
|
9
9
|
import { Link as fn } from "react-router-dom";
|
|
10
10
|
const pn = (e) => /* @__PURE__ */ i(
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),p=require("react"),$=require("styled-components"),f=require("./replay-index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("react/jsx-runtime"),p=require("react"),$=require("styled-components"),f=require("./replay-index-Dfnqt_IZ.js"),x=require("./replay-useAiChatQueries-D99tAUpY.js"),v=require("@redocly/theme"),M=require("./replay-db-CCBQadnT.js");require("@tanstack/react-query");const Ve=require("react-router-dom"),Fe=e=>e&&e.__esModule?e:{default:e},l=Fe($),Ge=e=>i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:i.jsx("path",{d:"M13.0094 7.61066L3.38435 2.79816C3.30892 2.76043 3.22418 2.74532 3.14035 2.75463C3.05652 2.76394 2.97717 2.79729 2.91186 2.85066C2.84948 2.90294 2.80292 2.97158 2.77742 3.04886C2.75191 3.12615 2.74847 3.20902 2.76748 3.28816L3.92685 7.56253H8.87498V8.43753H3.92685L2.74998 12.6988C2.73214 12.7649 2.73006 12.8342 2.7439 12.9013C2.75774 12.9683 2.78712 13.0312 2.82968 13.0848C2.87223 13.1384 2.92677 13.1813 2.98891 13.21C3.05106 13.2387 3.11907 13.2524 3.18748 13.25C3.25597 13.2496 3.3234 13.2331 3.38435 13.2019L13.0094 8.38941C13.081 8.35269 13.1412 8.29692 13.1832 8.22821C13.2252 8.15951 13.2474 8.08055 13.2474 8.00003C13.2474 7.91951 13.2252 7.84056 13.1832 7.77185C13.1412 7.70315 13.081 7.64737 13.0094 7.61066Z",fill:"white"})}),We=l.default(Ge).attrs({"data-component-name":"icons/SendIcon/SendIcon"})`
|
|
2
2
|
path {
|
|
3
3
|
fill: ${({color:e})=>f.getCssColorVariable(e)};
|
|
4
4
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as Qe } from "./replay-index-
|
|
1
|
+
import { F as Qe } from "./replay-index-BzzBKjHm.js";
|
|
2
2
|
import { h as Ve } from "./replay-history.schema-5ce6X0R1.js";
|
|
3
3
|
import { s as We } from "./replay-step-context.schema-DBk4jufr.js";
|
|
4
4
|
import { b as J, c as X, a as ee } from "./replay-ai-message-parts.schema-E9u9-nqr.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("./replay-index-BmotNqNI.js"),Te=require("./replay-history.schema-miM3Etuf.js"),Qe=require("./replay-step-context.schema-BuuXkAck.js"),C=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),t=require("./replay-indexes-Dqjl8m6C.js");class Ce{static[t.entityKind]="ConsoleLogWriter";write(e){console.log(e)}}class ve{static[t.entityKind]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Ce}logQuery(e,s){const i=s.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),r=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${r}`)}}class Le{static[t.entityKind]="NoopLogger";logQuery(){}}const re=Symbol.for("drizzle:PgInlineForeignKeys"),ne=Symbol.for("drizzle:EnableRLS");class $e extends t.Table{static[t.entityKind]="PgTable";static Symbol=Object.assign({},t.Table.Symbol,{InlineForeignKeys:re,EnableRLS:ne});[re]=[];[ne]=!1;[t.Table.Symbol.ExtraConfigBuilder]=void 0;[t.Table.Symbol.ExtraConfigColumns]={}}class Ne{static[t.entityKind]="PgPrimaryKeyBuilder";columns;name;constructor(e,s){this.columns=e,this.name=s}build(e){return new xe(e,this.columns,this.name)}}class xe{constructor(e,s,i){this.table=e,this.columns=s,this.name=i}static[t.entityKind]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$e.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}class de{constructor(e,s,i){this.sourceTable=e,this.referencedTable=s,this.relationName=i,this.referencedTableName=s[t.Table.Symbol.Name]}static[t.entityKind]="Relation";referencedTableName;fieldName}class fe{constructor(e,s){this.table=e,this.config=s}static[t.entityKind]="Relations"}class A extends de{constructor(e,s,i,r){super(e,s,i?.relationName),this.config=i,this.isNullable=r}static[t.entityKind]="One";withFieldName(e){const s=new A(this.sourceTable,this.referencedTable,this.config,this.isNullable);return s.fieldName=e,s}}class J extends de{constructor(e,s,i){super(e,s,i?.relationName),this.config=i}static[t.entityKind]="Many";withFieldName(e){const s=new J(this.sourceTable,this.referencedTable,this.config);return s.fieldName=e,s}}function Re(){return{and:t.and,between:t.between,eq:t.eq,exists:t.exists,gt:t.gt,gte:t.gte,ilike:t.ilike,inArray:t.inArray,isNull:t.isNull,isNotNull:t.isNotNull,like:t.like,lt:t.lt,lte:t.lte,ne:t.ne,not:t.not,notBetween:t.notBetween,notExists:t.notExists,notLike:t.notLike,notIlike:t.notIlike,notInArray:t.notInArray,or:t.or,sql:t.sql}}function Be(){return{sql:t.sql,asc:t.asc,desc:t.desc}}function _e(o,e){Object.keys(o).length===1&&"default"in o&&!t.is(o.default,t.Table)&&(o=o.default);const s={},i={},r={};for(const[n,a]of Object.entries(o))if(t.is(a,t.Table)){const l=t.getTableUniqueName(a),c=i[l];s[l]=n,r[n]={tsName:n,dbName:a[t.Table.Symbol.Name],schema:a[t.Table.Symbol.Schema],columns:a[t.Table.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(const h of Object.values(a[t.Table.Symbol.Columns]))h.primary&&r[n].primaryKey.push(h);const u=a[t.Table.Symbol.ExtraConfigBuilder]?.(a[t.Table.Symbol.ExtraConfigColumns]);if(u)for(const h of Object.values(u))t.is(h,Ne)&&r[n].primaryKey.push(...h.columns)}else if(t.is(a,fe)){const l=t.getTableUniqueName(a.table),c=s[l],u=a.config(e(a.table));let h;for(const[f,w]of Object.entries(u))if(c){const q=r[c];q.relations[f]=w}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[f]=w}return{tables:r,tableNamesMap:s}}function Z(o,e){return new fe(o,s=>Object.fromEntries(Object.entries(e(s)).map(([i,r])=>[i,r.withFieldName(i)])))}function Oe(o){return function(s,i){return new A(o,s,i,i?.fields.reduce((r,n)=>r&&n.notNull,!0)??!1)}}function Me(o){return function(s,i){return new J(o,s,i)}}function Ae(o,e,s){if(t.is(s,A)&&s.config)return{fields:s.config.fields,references:s.config.references};const i=e[t.getTableUniqueName(s.referencedTable)];if(!i)throw new Error(`Table "${s.referencedTable[t.Table.Symbol.Name]}" not found in schema`);const r=o[i];if(!r)throw new Error(`Table "${i}" not found in schema`);const n=s.sourceTable,a=e[t.getTableUniqueName(n)];if(!a)throw new Error(`Table "${n[t.Table.Symbol.Name]}" not found in schema`);const l=[];for(const c of Object.values(r.relations))(s.relationName&&s!==c&&c.relationName===s.relationName||!s.relationName&&c.referencedTable===s.sourceTable)&&l.push(c);if(l.length>1)throw s.relationName?new Error(`There are multiple relations with name "${s.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${s.sourceTable[t.Table.Symbol.Name]}". Please specify relation name`);if(l[0]&&t.is(l[0],A)&&l[0].config)return{fields:l[0].config.references,references:l[0].config.fields};throw new Error(`There is not enough information to infer relation "${a}.${s.fieldName}"`)}function Ke(o){return{one:Oe(o),many:Me(o)}}function Y(o,e,s,i,r=n=>n){const n={};for(const[a,l]of i.entries())if(l.isJson){const c=e.relations[l.tsKey],u=s[a],h=typeof u=="string"?JSON.parse(u):u;n[l.tsKey]=t.is(c,A)?h&&Y(o,o[l.relationTableTsKey],h,l.selection,r):h.map(f=>Y(o,o[l.relationTableTsKey],f,l.selection,r))}else{const c=r(s[a]),u=l.field;let h;t.is(u,t.Column)?h=u:t.is(u,t.SQL)?h=u.decoder:h=u.sql.decoder,n[l.tsKey]=c===null?null:h.mapFromDriverValue(c)}return n}class I{constructor(e){this.table=e}static[t.entityKind]="ColumnAliasProxyHandler";get(e,s){return s==="table"?this.table:e[s]}}class X{constructor(e,s){this.alias=e,this.replaceOriginalName=s}static[t.entityKind]="TableAliasProxyHandler";get(e,s){if(s===t.Table.Symbol.IsAlias)return!0;if(s===t.Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&s===t.Table.Symbol.OriginalName)return this.alias;if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],name:this.alias,isAlias:!0};if(s===t.Table.Symbol.Columns){const r=e[t.Table.Symbol.Columns];if(!r)return r;const n={};return Object.keys(r).map(a=>{n[a]=new Proxy(r[a],new I(new Proxy(e,this)))}),n}const i=e[s];return t.is(i,t.Column)?new Proxy(i,new I(new Proxy(e,this))):i}}function H(o,e){return new Proxy(o,new X(e,!1))}function B(o,e){return new Proxy(o,new I(new Proxy(o.table,new X(e,!1))))}function me(o,e){return new t.SQL.Aliased(k(o.sql,e),o.fieldAlias)}function k(o,e){return t.sql.join(o.queryChunks.map(s=>t.is(s,t.Column)?B(s,e):t.is(s,t.SQL)?k(s,e):t.is(s,t.SQL.Aliased)?me(s,e):s))}class Q{static[t.entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,s){if(s==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],selectedFields:new Proxy(e[t.ViewBaseConfig].selectedFields,this)};if(typeof s=="symbol")return e[s];const r=(t.is(e,t.Subquery)?e._.selectedFields:t.is(e,t.View)?e[t.ViewBaseConfig].selectedFields:e)[s];if(t.is(r,t.SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!r.isSelectionField)return r.sql;const n=r.clone();return n.isSelectionField=!0,n}if(t.is(r,t.SQL)){if(this.config.sqlBehavior==="sql")return r;throw new Error(`You tried to reference "${s}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return t.is(r,t.Column)?this.config.alias?new Proxy(r,new I(new Proxy(r.table,new X(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!="object"||r===null?r:new Proxy(r,new Q(this.config))}}class K{static[t.entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}then(e,s){return this.execute().then(e,s)}}function M(o){return t.is(o,t.SQLiteTable)?[`${o[t.Table.Symbol.BaseName]}`]:t.is(o,t.Subquery)?o._.usedTables??[]:t.is(o,t.SQL)?o.usedTables??[]:[]}class ae extends K{constructor(e,s,i,r){super(),this.table=e,this.session=s,this.dialect=i,this.config={table:e,withList:r}}static[t.entityKind]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.orderBy=i}else{const s=e;this.config.orderBy=s}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:M(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}function Pe(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(s=>s.toLowerCase()).join("_")}function je(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((s,i,r)=>{const n=r===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return s+n},"")}function Ee(o){return o}class Fe{static[t.entityKind]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Pe:e==="camelCase"?je:Ee}getColumnCasing(e){if(!e.keyAsName)return e.name;const s=e.table[t.Table.Symbol.Schema]??"public",i=e.table[t.Table.Symbol.OriginalName],r=`${s}.${i}.${e.name}`;return this.cache[r]||this.cacheTable(e.table),this.cache[r]}cacheTable(e){const s=e[t.Table.Symbol.Schema]??"public",i=e[t.Table.Symbol.OriginalName],r=`${s}.${i}`;if(!this.cachedTables[r]){for(const n of Object.values(e[t.Table.Symbol.Columns])){const a=`${r}.${n.name}`;this.cache[a]=this.convert(n.name)}this.cachedTables[r]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ee extends Error{static[t.entityKind]="DrizzleError";constructor({message:e,cause:s}){super(e),this.name="DrizzleError",this.cause=s}}class _ extends Error{constructor(e,s,i){super(`Failed query: ${e}
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ie=require("./replay-index-Dfnqt_IZ.js"),Te=require("./replay-history.schema-miM3Etuf.js"),Qe=require("./replay-step-context.schema-BuuXkAck.js"),C=require("./replay-ai-message-parts.schema-BBdjwldJ.js"),t=require("./replay-indexes-Dqjl8m6C.js");class Ce{static[t.entityKind]="ConsoleLogWriter";write(e){console.log(e)}}class ve{static[t.entityKind]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Ce}logQuery(e,s){const i=s.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),r=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${r}`)}}class Le{static[t.entityKind]="NoopLogger";logQuery(){}}const re=Symbol.for("drizzle:PgInlineForeignKeys"),ne=Symbol.for("drizzle:EnableRLS");class $e extends t.Table{static[t.entityKind]="PgTable";static Symbol=Object.assign({},t.Table.Symbol,{InlineForeignKeys:re,EnableRLS:ne});[re]=[];[ne]=!1;[t.Table.Symbol.ExtraConfigBuilder]=void 0;[t.Table.Symbol.ExtraConfigColumns]={}}class Ne{static[t.entityKind]="PgPrimaryKeyBuilder";columns;name;constructor(e,s){this.columns=e,this.name=s}build(e){return new xe(e,this.columns,this.name)}}class xe{constructor(e,s,i){this.table=e,this.columns=s,this.name=i}static[t.entityKind]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[$e.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}class de{constructor(e,s,i){this.sourceTable=e,this.referencedTable=s,this.relationName=i,this.referencedTableName=s[t.Table.Symbol.Name]}static[t.entityKind]="Relation";referencedTableName;fieldName}class fe{constructor(e,s){this.table=e,this.config=s}static[t.entityKind]="Relations"}class A extends de{constructor(e,s,i,r){super(e,s,i?.relationName),this.config=i,this.isNullable=r}static[t.entityKind]="One";withFieldName(e){const s=new A(this.sourceTable,this.referencedTable,this.config,this.isNullable);return s.fieldName=e,s}}class J extends de{constructor(e,s,i){super(e,s,i?.relationName),this.config=i}static[t.entityKind]="Many";withFieldName(e){const s=new J(this.sourceTable,this.referencedTable,this.config);return s.fieldName=e,s}}function Re(){return{and:t.and,between:t.between,eq:t.eq,exists:t.exists,gt:t.gt,gte:t.gte,ilike:t.ilike,inArray:t.inArray,isNull:t.isNull,isNotNull:t.isNotNull,like:t.like,lt:t.lt,lte:t.lte,ne:t.ne,not:t.not,notBetween:t.notBetween,notExists:t.notExists,notLike:t.notLike,notIlike:t.notIlike,notInArray:t.notInArray,or:t.or,sql:t.sql}}function Be(){return{sql:t.sql,asc:t.asc,desc:t.desc}}function _e(o,e){Object.keys(o).length===1&&"default"in o&&!t.is(o.default,t.Table)&&(o=o.default);const s={},i={},r={};for(const[n,a]of Object.entries(o))if(t.is(a,t.Table)){const l=t.getTableUniqueName(a),c=i[l];s[l]=n,r[n]={tsName:n,dbName:a[t.Table.Symbol.Name],schema:a[t.Table.Symbol.Schema],columns:a[t.Table.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(const h of Object.values(a[t.Table.Symbol.Columns]))h.primary&&r[n].primaryKey.push(h);const u=a[t.Table.Symbol.ExtraConfigBuilder]?.(a[t.Table.Symbol.ExtraConfigColumns]);if(u)for(const h of Object.values(u))t.is(h,Ne)&&r[n].primaryKey.push(...h.columns)}else if(t.is(a,fe)){const l=t.getTableUniqueName(a.table),c=s[l],u=a.config(e(a.table));let h;for(const[f,w]of Object.entries(u))if(c){const q=r[c];q.relations[f]=w}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[f]=w}return{tables:r,tableNamesMap:s}}function Z(o,e){return new fe(o,s=>Object.fromEntries(Object.entries(e(s)).map(([i,r])=>[i,r.withFieldName(i)])))}function Oe(o){return function(s,i){return new A(o,s,i,i?.fields.reduce((r,n)=>r&&n.notNull,!0)??!1)}}function Me(o){return function(s,i){return new J(o,s,i)}}function Ae(o,e,s){if(t.is(s,A)&&s.config)return{fields:s.config.fields,references:s.config.references};const i=e[t.getTableUniqueName(s.referencedTable)];if(!i)throw new Error(`Table "${s.referencedTable[t.Table.Symbol.Name]}" not found in schema`);const r=o[i];if(!r)throw new Error(`Table "${i}" not found in schema`);const n=s.sourceTable,a=e[t.getTableUniqueName(n)];if(!a)throw new Error(`Table "${n[t.Table.Symbol.Name]}" not found in schema`);const l=[];for(const c of Object.values(r.relations))(s.relationName&&s!==c&&c.relationName===s.relationName||!s.relationName&&c.referencedTable===s.sourceTable)&&l.push(c);if(l.length>1)throw s.relationName?new Error(`There are multiple relations with name "${s.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${s.sourceTable[t.Table.Symbol.Name]}". Please specify relation name`);if(l[0]&&t.is(l[0],A)&&l[0].config)return{fields:l[0].config.references,references:l[0].config.fields};throw new Error(`There is not enough information to infer relation "${a}.${s.fieldName}"`)}function Ke(o){return{one:Oe(o),many:Me(o)}}function Y(o,e,s,i,r=n=>n){const n={};for(const[a,l]of i.entries())if(l.isJson){const c=e.relations[l.tsKey],u=s[a],h=typeof u=="string"?JSON.parse(u):u;n[l.tsKey]=t.is(c,A)?h&&Y(o,o[l.relationTableTsKey],h,l.selection,r):h.map(f=>Y(o,o[l.relationTableTsKey],f,l.selection,r))}else{const c=r(s[a]),u=l.field;let h;t.is(u,t.Column)?h=u:t.is(u,t.SQL)?h=u.decoder:h=u.sql.decoder,n[l.tsKey]=c===null?null:h.mapFromDriverValue(c)}return n}class I{constructor(e){this.table=e}static[t.entityKind]="ColumnAliasProxyHandler";get(e,s){return s==="table"?this.table:e[s]}}class X{constructor(e,s){this.alias=e,this.replaceOriginalName=s}static[t.entityKind]="TableAliasProxyHandler";get(e,s){if(s===t.Table.Symbol.IsAlias)return!0;if(s===t.Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&s===t.Table.Symbol.OriginalName)return this.alias;if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],name:this.alias,isAlias:!0};if(s===t.Table.Symbol.Columns){const r=e[t.Table.Symbol.Columns];if(!r)return r;const n={};return Object.keys(r).map(a=>{n[a]=new Proxy(r[a],new I(new Proxy(e,this)))}),n}const i=e[s];return t.is(i,t.Column)?new Proxy(i,new I(new Proxy(e,this))):i}}function H(o,e){return new Proxy(o,new X(e,!1))}function B(o,e){return new Proxy(o,new I(new Proxy(o.table,new X(e,!1))))}function me(o,e){return new t.SQL.Aliased(k(o.sql,e),o.fieldAlias)}function k(o,e){return t.sql.join(o.queryChunks.map(s=>t.is(s,t.Column)?B(s,e):t.is(s,t.SQL)?k(s,e):t.is(s,t.SQL.Aliased)?me(s,e):s))}class Q{static[t.entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,s){if(s==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(s===t.ViewBaseConfig)return{...e[t.ViewBaseConfig],selectedFields:new Proxy(e[t.ViewBaseConfig].selectedFields,this)};if(typeof s=="symbol")return e[s];const r=(t.is(e,t.Subquery)?e._.selectedFields:t.is(e,t.View)?e[t.ViewBaseConfig].selectedFields:e)[s];if(t.is(r,t.SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!r.isSelectionField)return r.sql;const n=r.clone();return n.isSelectionField=!0,n}if(t.is(r,t.SQL)){if(this.config.sqlBehavior==="sql")return r;throw new Error(`You tried to reference "${s}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return t.is(r,t.Column)?this.config.alias?new Proxy(r,new I(new Proxy(r.table,new X(this.config.alias,this.config.replaceOriginalName??!1)))):r:typeof r!="object"||r===null?r:new Proxy(r,new Q(this.config))}}class K{static[t.entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(s=>(e?.(),s),s=>{throw e?.(),s})}then(e,s){return this.execute().then(e,s)}}function M(o){return t.is(o,t.SQLiteTable)?[`${o[t.Table.Symbol.BaseName]}`]:t.is(o,t.Subquery)?o._.usedTables??[]:t.is(o,t.SQL)?o.usedTables??[]:[]}class ae extends K{constructor(e,s,i,r){super(),this.table=e,this.session=s,this.dialect=i,this.config={table:e,withList:r}}static[t.entityKind]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){const s=e[0](new Proxy(this.config.table[t.Table.Symbol.Columns],new Q({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(s)?s:[s];this.config.orderBy=i}else{const s=e;this.config.orderBy=s}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[t.SQLiteTable.Symbol.Columns]){return this.config.returning=t.orderSelectedFields(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...s}=this.dialect.sqlToQuery(this.getSQL());return s}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:M(this.config.table)})}prepare(){return this._prepare(!1)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}function Pe(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(s=>s.toLowerCase()).join("_")}function je(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((s,i,r)=>{const n=r===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return s+n},"")}function Ee(o){return o}class Fe{static[t.entityKind]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Pe:e==="camelCase"?je:Ee}getColumnCasing(e){if(!e.keyAsName)return e.name;const s=e.table[t.Table.Symbol.Schema]??"public",i=e.table[t.Table.Symbol.OriginalName],r=`${s}.${i}.${e.name}`;return this.cache[r]||this.cacheTable(e.table),this.cache[r]}cacheTable(e){const s=e[t.Table.Symbol.Schema]??"public",i=e[t.Table.Symbol.OriginalName],r=`${s}.${i}`;if(!this.cachedTables[r]){for(const n of Object.values(e[t.Table.Symbol.Columns])){const a=`${r}.${n.name}`;this.cache[a]=this.convert(n.name)}this.cachedTables[r]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class ee extends Error{static[t.entityKind]="DrizzleError";constructor({message:e,cause:s}){super(e),this.name="DrizzleError",this.cause=s}}class _ extends Error{constructor(e,s,i){super(`Failed query: ${e}
|
|
2
2
|
params: ${s}`),this.query=e,this.params=s,this.cause=i,Error.captureStackTrace(this,_),i&&(this.cause=i)}}class Ie extends ee{static[t.entityKind]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class te extends t.View{static[t.entityKind]="SQLiteViewBase"}class D{static[t.entityKind]="SQLiteDialect";casing;constructor(e){this.casing=new Fe(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;const s=[t.sql`with `];for(const[i,r]of e.entries())s.push(t.sql`${t.sql.identifier(r._.alias)} as (${r._.sql})`),i<e.length-1&&s.push(t.sql`, `);return s.push(t.sql` `),t.sql.join(s)}buildDeleteQuery({table:e,where:s,returning:i,withList:r,limit:n,orderBy:a}){const l=this.buildWithCTE(r),c=i?t.sql` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,u=s?t.sql` where ${s}`:void 0,h=this.buildOrderBy(a),f=this.buildLimit(n);return t.sql`${l}delete from ${e}${u}${c}${h}${f}`}buildUpdateSet(e,s){const i=e[t.Table.Symbol.Columns],r=Object.keys(i).filter(a=>s[a]!==void 0||i[a]?.onUpdateFn!==void 0),n=r.length;return t.sql.join(r.flatMap((a,l)=>{const c=i[a],u=c.onUpdateFn?.(),h=s[a]??(t.is(u,t.SQL)?u:t.sql.param(u,c)),f=t.sql`${t.sql.identifier(this.casing.getColumnCasing(c))} = ${h}`;return l<n-1?[f,t.sql.raw(", ")]:[f]}))}buildUpdateQuery({table:e,set:s,where:i,returning:r,withList:n,joins:a,from:l,limit:c,orderBy:u}){const h=this.buildWithCTE(n),f=this.buildUpdateSet(e,s),w=l&&t.sql.join([t.sql.raw(" from "),this.buildFromTable(l)]),q=this.buildJoins(a),S=r?t.sql` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,g=i?t.sql` where ${i}`:void 0,p=this.buildOrderBy(u),b=this.buildLimit(c);return t.sql`${h}update ${e} set ${f}${w}${q}${g}${S}${p}${b}`}buildSelection(e,{isSingleTable:s=!1}={}){const i=e.length,r=e.flatMap(({field:n},a)=>{const l=[];if(t.is(n,t.SQL.Aliased)&&n.isSelectionField)l.push(t.sql.identifier(n.fieldAlias));else if(t.is(n,t.SQL.Aliased)||t.is(n,t.SQL)){const c=t.is(n,t.SQL.Aliased)?n.sql:n;s?l.push(new t.SQL(c.queryChunks.map(u=>t.is(u,t.Column)?t.sql.identifier(this.casing.getColumnCasing(u)):u))):l.push(c),t.is(n,t.SQL.Aliased)&&l.push(t.sql` as ${t.sql.identifier(n.fieldAlias)}`)}else if(t.is(n,t.Column)){const c=n.table[t.Table.Symbol.Name];n.columnType==="SQLiteNumericBigInt"?s?l.push(t.sql`cast(${t.sql.identifier(this.casing.getColumnCasing(n))} as text)`):l.push(t.sql`cast(${t.sql.identifier(c)}.${t.sql.identifier(this.casing.getColumnCasing(n))} as text)`):s?l.push(t.sql.identifier(this.casing.getColumnCasing(n))):l.push(t.sql`${t.sql.identifier(c)}.${t.sql.identifier(this.casing.getColumnCasing(n))}`)}else if(t.is(n,t.Subquery)){const c=Object.entries(n._.selectedFields);if(c.length===1){const u=c[0][1],h=t.is(u,t.SQL)?u.decoder:t.is(u,t.Column)?{mapFromDriverValue:f=>u.mapFromDriverValue(f)}:u.sql.decoder;h&&(n._.sql.decoder=h)}l.push(n)}return a<i-1&&l.push(t.sql`, `),l});return t.sql.join(r)}buildJoins(e){if(!e||e.length===0)return;const s=[];if(e)for(const[i,r]of e.entries()){i===0&&s.push(t.sql` `);const n=r.table,a=r.on?t.sql` on ${r.on}`:void 0;if(t.is(n,t.SQLiteTable)){const l=n[t.SQLiteTable.Symbol.Name],c=n[t.SQLiteTable.Symbol.Schema],u=n[t.SQLiteTable.Symbol.OriginalName],h=l===u?void 0:r.alias;s.push(t.sql`${t.sql.raw(r.joinType)} join ${c?t.sql`${t.sql.identifier(c)}.`:void 0}${t.sql.identifier(u)}${h&&t.sql` ${t.sql.identifier(h)}`}${a}`)}else s.push(t.sql`${t.sql.raw(r.joinType)} join ${n}${a}`);i<e.length-1&&s.push(t.sql` `)}return t.sql.join(s)}buildLimit(e){return typeof e=="object"||typeof e=="number"&&e>=0?t.sql` limit ${e}`:void 0}buildOrderBy(e){const s=[];if(e)for(const[i,r]of e.entries())s.push(r),i<e.length-1&&s.push(t.sql`, `);return s.length>0?t.sql` order by ${t.sql.join(s)}`:void 0}buildFromTable(e){return t.is(e,t.Table)&&e[t.Table.Symbol.IsAlias]?t.sql`${t.sql`${t.sql.identifier(e[t.Table.Symbol.Schema]??"")}.`.if(e[t.Table.Symbol.Schema])}${t.sql.identifier(e[t.Table.Symbol.OriginalName])} ${t.sql.identifier(e[t.Table.Symbol.Name])}`:e}buildSelectQuery({withList:e,fields:s,fieldsFlat:i,where:r,having:n,table:a,joins:l,orderBy:c,groupBy:u,limit:h,offset:f,distinct:w,setOperators:q}){const S=i??t.orderSelectedFields(s);for(const $ of S)if(t.is($.field,t.Column)&&t.getTableName($.field.table)!==(t.is(a,t.Subquery)?a._.alias:t.is(a,te)?a[t.ViewBaseConfig].name:t.is(a,t.SQL)?void 0:t.getTableName(a))&&!(N=>l?.some(({alias:E})=>E===(N[t.Table.Symbol.IsAlias]?t.getTableName(N):N[t.Table.Symbol.BaseName])))($.field.table)){const N=t.getTableName($.field.table);throw new Error(`Your "${$.path.join("->")}" field references a column "${N}"."${$.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}const g=!l||l.length===0,p=this.buildWithCTE(e),b=w?t.sql` distinct`:void 0,v=this.buildSelection(S,{isSingleTable:g}),T=this.buildFromTable(a),m=this.buildJoins(l),x=r?t.sql` where ${r}`:void 0,L=n?t.sql` having ${n}`:void 0,d=[];if(u)for(const[$,N]of u.entries())d.push(N),$<u.length-1&&d.push(t.sql`, `);const y=d.length>0?t.sql` group by ${t.sql.join(d)}`:void 0,R=this.buildOrderBy(c),j=this.buildLimit(h),W=f?t.sql` offset ${f}`:void 0,P=t.sql`${p}select${b} ${v} from ${T}${m}${x}${y}${L}${R}${j}${W}`;return q.length>0?this.buildSetOperations(P,q):P}buildSetOperations(e,s){const[i,...r]=s;if(!i)throw new Error("Cannot pass undefined values to any set operator");return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:s,isAll:i,rightSelect:r,limit:n,orderBy:a,offset:l}}){const c=t.sql`${e.getSQL()} `,u=t.sql`${r.getSQL()}`;let h;if(a&&a.length>0){const S=[];for(const g of a)if(t.is(g,t.SQLiteColumn))S.push(t.sql.identifier(g.name));else if(t.is(g,t.SQL)){for(let p=0;p<g.queryChunks.length;p++){const b=g.queryChunks[p];t.is(b,t.SQLiteColumn)&&(g.queryChunks[p]=t.sql.identifier(this.casing.getColumnCasing(b)))}S.push(t.sql`${g}`)}else S.push(t.sql`${g}`);h=t.sql` order by ${t.sql.join(S,t.sql`, `)}`}const f=typeof n=="object"||typeof n=="number"&&n>=0?t.sql` limit ${n}`:void 0,w=t.sql.raw(`${s} ${i?"all ":""}`),q=l?t.sql` offset ${l}`:void 0;return t.sql`${c}${w}${u}${h}${f}${q}`}buildInsertQuery({table:e,values:s,onConflict:i,returning:r,withList:n,select:a}){const l=[],c=e[t.Table.Symbol.Columns],u=Object.entries(c).filter(([g,p])=>!p.shouldDisableInsert()),h=u.map(([,g])=>t.sql.identifier(this.casing.getColumnCasing(g)));if(a){const g=s;t.is(g,t.SQL)?l.push(g):l.push(g.getSQL())}else{const g=s;l.push(t.sql.raw("values "));for(const[p,b]of g.entries()){const v=[];for(const[T,m]of u){const x=b[T];if(x===void 0||t.is(x,t.Param)&&x.value===void 0){let L;if(m.default!==null&&m.default!==void 0)L=t.is(m.default,t.SQL)?m.default:t.sql.param(m.default,m);else if(m.defaultFn!==void 0){const d=m.defaultFn();L=t.is(d,t.SQL)?d:t.sql.param(d,m)}else if(!m.default&&m.onUpdateFn!==void 0){const d=m.onUpdateFn();L=t.is(d,t.SQL)?d:t.sql.param(d,m)}else L=t.sql`null`;v.push(L)}else v.push(x)}l.push(v),p<g.length-1&&l.push(t.sql`, `)}}const f=this.buildWithCTE(n),w=t.sql.join(l),q=r?t.sql` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,S=i?.length?t.sql.join(i):void 0;return t.sql`${f}insert into ${e} ${h} ${w}${S}${q}`}sqlToQuery(e,s){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:s})}buildRelationalQuery({fullSchema:e,schema:s,tableNamesMap:i,table:r,tableConfig:n,queryConfig:a,tableAlias:l,nestedQueryRelation:c,joinOn:u}){let h=[],f,w,q=[],S;const g=[];if(a===!0)h=Object.entries(n.columns).map(([v,T])=>({dbKey:T.name,tsKey:v,field:B(T,l),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const b=Object.fromEntries(Object.entries(n.columns).map(([d,y])=>[d,B(y,l)]));if(a.where){const d=typeof a.where=="function"?a.where(b,Re()):a.where;S=d&&k(d,l)}const v=[];let T=[];if(a.columns){let d=!1;for(const[y,R]of Object.entries(a.columns))R!==void 0&&y in n.columns&&(!d&&R===!0&&(d=!0),T.push(y));T.length>0&&(T=d?T.filter(y=>a.columns?.[y]===!0):Object.keys(n.columns).filter(y=>!T.includes(y)))}else T=Object.keys(n.columns);for(const d of T){const y=n.columns[d];v.push({tsKey:d,value:y})}let m=[];a.with&&(m=Object.entries(a.with).filter(d=>!!d[1]).map(([d,y])=>({tsKey:d,queryConfig:y,relation:n.relations[d]})));let x;if(a.extras){x=typeof a.extras=="function"?a.extras(b,{sql:t.sql}):a.extras;for(const[d,y]of Object.entries(x))v.push({tsKey:d,value:me(y,l)})}for(const{tsKey:d,value:y}of v)h.push({dbKey:t.is(y,t.SQL.Aliased)?y.fieldAlias:n.columns[d].name,tsKey:d,field:t.is(y,t.Column)?B(y,l):y,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof a.orderBy=="function"?a.orderBy(b,Be()):a.orderBy??[];Array.isArray(L)||(L=[L]),q=L.map(d=>t.is(d,t.Column)?B(d,l):k(d,l)),f=a.limit,w=a.offset;for(const{tsKey:d,queryConfig:y,relation:R}of m){const j=Ae(s,i,R),W=t.getTableUniqueName(R.referencedTable),P=i[W],$=`${l}_${d}`,N=t.and(...j.fields.map((we,qe)=>t.eq(B(j.references[qe],$),B(we,l)))),E=this.buildRelationalQuery({fullSchema:e,schema:s,tableNamesMap:i,table:e[P],tableConfig:s[P],queryConfig:t.is(R,A)?y===!0?{limit:1}:{...y,limit:1}:y,tableAlias:$,joinOn:N,nestedQueryRelation:R}),Se=t.sql`(${E.sql})`.as(d);h.push({dbKey:d,tsKey:d,field:Se,relationTableTsKey:P,isJson:!0,selection:E.selection})}}if(h.length===0)throw new ee({message:`No fields selected for table "${n.tsName}" ("${l}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let p;if(S=t.and(u,S),c){let b=t.sql`json_array(${t.sql.join(h.map(({field:m})=>t.is(m,t.SQLiteColumn)?t.sql.identifier(this.casing.getColumnCasing(m)):t.is(m,t.SQL.Aliased)?m.sql:m),t.sql`, `)})`;t.is(c,J)&&(b=t.sql`coalesce(json_group_array(${b}), json_array())`);const v=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:h}];f!==void 0||w!==void 0||q.length>0?(p=this.buildSelectQuery({table:H(r,l),fields:{},fieldsFlat:[{path:[],field:t.sql.raw("*")}],where:S,limit:f,offset:w,orderBy:q,setOperators:[]}),S=void 0,f=void 0,w=void 0,q=void 0):p=H(r,l),p=this.buildSelectQuery({table:t.is(p,t.SQLiteTable)?p:new t.Subquery(p,{},l),fields:{},fieldsFlat:v.map(({field:m})=>({path:[],field:t.is(m,t.Column)?B(m,l):m})),joins:g,where:S,limit:f,offset:w,orderBy:q,setOperators:[]})}else p=this.buildSelectQuery({table:H(r,l),fields:{},fieldsFlat:h.map(({field:b})=>({path:[],field:t.is(b,t.Column)?B(b,l):b})),joins:g,where:S,limit:f,offset:w,orderBy:q,setOperators:[]});return{tableTsKey:n.tsName,sql:p,selection:h}}}class ke extends D{static[t.entityKind]="SQLiteSyncDialect";migrate(e,s,i){const r=i===void 0||typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=t.sql`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS ${t.sql.identifier(r)} (
|
|
4
4
|
id SERIAL PRIMARY KEY,
|
|
@@ -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 { t as g, q as _, S, x as M, y as z, z as I, D as W, B as K } from "./replay-index-
|
|
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-C5yvtnXA.js";
|
|
2
|
+
import { t as g, q as _, S, x as M, y as z, z as I, D as W, B as K } from "./replay-index-BzzBKjHm.js";
|
|
3
|
+
import { g as U } from "./replay-db-DfOjLqsq.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 = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("./replay-create-model-CmRk68RD.js"),l=require("./replay-index-BmotNqNI.js"),j=require("./replay-db-BfSnfWcb.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-CBCmuEKC.js"),l=require("./replay-index-Dfnqt_IZ.js"),j=require("./replay-db-CCBQadnT.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-
|
|
1
|
+
"use strict";const i=require("./replay-index-Dfnqt_IZ.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 { R as nd, aD as zh, E as Kr } from "./replay-index-
|
|
1
|
+
import { R as nd, aD as zh, E as Kr } from "./replay-index-BzzBKjHm.js";
|
|
2
2
|
var ad = "vercel.ai.error", Fh = Symbol.for(ad), Js, Ks, ve = class rd extends (Ks = Error, Js = Fh, Ks) {
|
|
3
3
|
/**
|
|
4
4
|
* Creates an AI SDK Error.
|
|
@@ -13622,7 +13622,7 @@ async function KT() {
|
|
|
13622
13622
|
if (hf())
|
|
13623
13623
|
return fi == null && (fi = import(
|
|
13624
13624
|
/* webpackIgnore: true */
|
|
13625
|
-
"./replay-index-
|
|
13625
|
+
"./replay-index-BzzBKjHm.js"
|
|
13626
13626
|
).then((e) => e.bb).catch(() => {
|
|
13627
13627
|
})), fi;
|
|
13628
13628
|
}
|