@redocly/openapi-docs 3.24.0-next.5 → 3.24.0-next.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/redocly-openapi-docs.min.AiChatProvider-C_OmERaa.js +32 -0
- package/dist/redocly-openapi-docs.min.AiChatSqliteDBStorage-C5E-x8f4.js +1 -0
- package/dist/redocly-openapi-docs.min.AiPanel-Z2Zw-OOK.js +754 -0
- package/dist/redocly-openapi-docs.min.HistorySqliteDBStorage-DYnaxLim.js +1 -0
- package/dist/redocly-openapi-docs.min.SqliteDBStorage-B6uym4Oj.js +14 -0
- package/dist/redocly-openapi-docs.min.StepContextSqliteDBStorage-DTB5U2yh.js +1 -0
- package/dist/redocly-openapi-docs.min.ai-chat-mappers-y6k4QA37.js +1 -0
- package/dist/redocly-openapi-docs.min.ai-message-parts.schema-C7fjQhYX.js +1 -0
- package/dist/redocly-openapi-docs.min.external-resolver-6xHVd9y7.js +2 -0
- package/dist/redocly-openapi-docs.min.history.schema-DzAAX18S.js +1 -0
- package/dist/redocly-openapi-docs.min.index-B2kW1MJX.js +1 -0
- package/dist/redocly-openapi-docs.min.index-D5tgmAoY.js +1 -0
- package/dist/redocly-openapi-docs.min.index-DHNqz_Gi.js +7694 -0
- package/dist/redocly-openapi-docs.min.index-DkqHu0CX.js +1 -0
- package/dist/redocly-openapi-docs.min.indexes-Bp4ld5gB.js +1 -0
- package/dist/redocly-openapi-docs.min.js +1 -21189
- package/dist/redocly-openapi-docs.min.lint-CmpdR_qH.js +181 -0
- package/dist/redocly-openapi-docs.min.lint-graphql-CAO-eUMC.js +3 -0
- package/dist/redocly-openapi-docs.min.respect-run-DjAvzRiR.js +78 -0
- package/dist/redocly-openapi-docs.min.standalone-C6JXws-S.js +12087 -0
- package/dist/redocly-openapi-docs.min.step-context.schema-DEgzIgw0.js +1 -0
- package/dist/redocly-openapi-docs.min.tauri-path-DySEV5MH.js +1 -0
- package/dist/redocly-openapi-docs.min.useAiChatQueries-CYikEfuU.js +358 -0
- package/lib/components/Callbacks/CallbackSummary.js +1 -1
- package/lib/components/Callbacks/CallbacksList.js +1 -1
- package/lib/models/field.js +1 -1
- package/lib/models/schema.js +2 -2
- package/package.json +4 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import{U as v,V as T,ax as x,M as _t,c as Qt,r as l,j as at}from"./redocly-openapi-docs.min.standalone-C6JXws-S.js";import{T as Gt,c as rt,D as Ht,a as Vt,u as mt,b as gt,d as A,A as ft,I as Yt,e as E,f as Xt,g as Zt,h as te,i as wt,j as ee,k as ne,l as oe,m as ae,n as Tt,o as st,p as ht,q as At,r as re,s as Mt,R as it,t as se,v as yt,w as ie,x as le}from"./redocly-openapi-docs.min.index-DHNqz_Gi.js";import{c as St,p as ue,g as pe,T as ce,i as de,a as me,s as ge,A as fe,b as he,r as ye,d as Se,e as ve,o as be,f as Ie,w as ke,m as Ce,h as xe,u as _e,j as we,k as Te,l as Ae,D as Me,n as Oe,q as Ee,t as Re,v as je,x as qe,y as Ne}from"./redocly-openapi-docs.min.useAiChatQueries-CYikEfuU.js";import{b as Ot,g as Et}from"./redocly-openapi-docs.min.ai-chat-mappers-y6k4QA37.js";function R(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 Rt(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 jt(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 $e(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 s=t.output;let i;return s&&(s.type==="text"||s.type==="error-text"||s.type==="json"||s.type==="error-json"?i=s.value:s.type==="execution-denied"?i={denied:!0,reason:s.reason}:i=s),{type:"tool_call_response",id:(n=t.toolCallId)!=null?n:null,response:i}}case"file":{const s=t.data,i=(()=>{if(typeof s=="object"&&s!==null&&!(s instanceof URL)&&!(s instanceof Uint8Array)&&!(s instanceof ArrayBuffer)&&"type"in s)switch(s.type){case"data":return s.data;case"url":return s.url;case"text":return s.text;default:return""}return s})();let u;if(i instanceof Uint8Array)u=St(i);else if(typeof i=="string"){if(i.startsWith("http://")||i.startsWith("https://"))return{type:"uri",modality:j(t.mediaType),mime_type:(o=t.mediaType)!=null?o:null,uri:i};u=i}else{if(i instanceof URL)return{type:"uri",modality:j(t.mediaType),mime_type:(r=t.mediaType)!=null?r:null,uri:i.toString()};u=String(i)}return{type:"blob",modality:j(t.mediaType),mime_type:(a=t.mediaType)!=null?a:null,content:u}}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 j(t){return!t||t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"image"}function Pe(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($e);return{role:e.role,parts:n}})}function vt({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=qt(o);r&&n.push(r)}if(e)for(const o of e){const r=qt(o);r&&n.push(r)}return n}function qt(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(e=>{var n,o,r,a,s,i,u,d;switch(e.type){case"text":return{type:"text",content:e.text};case"image":{const c=e.image;return c instanceof URL?{type:"uri",modality:"image",mime_type:(n=e.mediaType)!=null?n:null,uri:c.toString()}:typeof c=="string"?c.startsWith("http://")||c.startsWith("https://")?{type:"uri",modality:"image",mime_type:(o=e.mediaType)!=null?o:null,uri:c}:{type:"blob",modality:"image",mime_type:(r=e.mediaType)!=null?r:null,content:c}:{type:"blob",modality:"image",mime_type:(a=e.mediaType)!=null?a:null,content:St(c)}}case"file":{const c=e.data,p=(()=>{if(typeof c=="object"&&c!==null&&!(c instanceof URL)&&!(c instanceof Uint8Array)&&!(c instanceof ArrayBuffer)&&"type"in c)switch(c.type){case"data":return c.data;case"url":return c.url;case"text":return c.text;default:return""}return c})();return p instanceof URL?{type:"uri",modality:j(e.mediaType),mime_type:(s=e.mediaType)!=null?s:null,uri:p.toString()}:typeof p=="string"?p.startsWith("http://")||p.startsWith("https://")?{type:"uri",modality:j(e.mediaType),mime_type:(i=e.mediaType)!=null?i:null,uri:p}:{type:"blob",modality:j(e.mediaType),mime_type:(u=e.mediaType)!=null?u:null,content:p}:{type:"blob",modality:j(e.mediaType),mime_type:(d=e.mediaType)!=null?d:null,content:St(p)}}default:return{type:String(e.type)}}})};if(t.role==="assistant")return typeof t.content=="string"?{role:"assistant",parts:[{type:"text",content:t.content}]}:{role:"assistant",parts:t.content.map(e=>{var n,o;switch(e.type){case"text":return{type:"text",content:e.text};case"reasoning":return{type:"reasoning",content:e.text};case"tool-call":return{type:"tool_call",id:(n=e.toolCallId)!=null?n:null,name:e.toolName,arguments:e.input};case"tool-result":{const r=e.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=e.toolCallId)!=null?o:null,response:a}}default:return{type:String(e.type)}}})};if(t.role==="tool")return{role:"tool",parts:t.content.map(e=>{var n;if(e.type==="tool-result"){const o=e.output;let r;return o&&(o.type==="text"||o.type==="error-text"||o.type==="json"||o.type==="error-json"?r=o.value:o.type==="execution-denied"?r={denied:!0,reason:o.reason}:r=o),{type:"tool_call_response",id:(n=e.toolCallId)!=null?n:null,response:r}}return{type:String(e.type)}})}}}function Nt({text:t,reasoning:e,toolCalls:n,files:o,finishReason:r}){const a=[];if(e)for(const s of e)"text"in s&&s.text&&a.push({type:"reasoning",content:s.text});if(t!=null&&t.length>0&&a.push({type:"text",content:t}),n)for(const s of n)a.push({type:"tool_call",id:s.toolCallId,name:s.toolName,arguments:s.input});if(o)for(const s of o)a.push({type:"blob",modality:j(s.mediaType),mime_type:s.mediaType,content:s.base64});return[{role:"assistant",parts:a,finish_reason:Pt(r)}]}function $t({objectText:t,finishReason:e}){return[{role:"assistant",parts:[{type:"text",content:t}],finish_reason:Pt(e)}]}function Pt(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 U(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:_t.ERROR,message:e.message})):t.setStatus({code:_t.ERROR})}function De(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function lt(t){if(!Array.isArray(t))return t;const e=new Set(t.filter(De).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 We(t){const e={};for(const[n,o]of Object.entries(t??{})){if(o==null)continue;const r=lt(o);r!=null&&(e[n]=r)}return e}function Je(t){return t?.isEnabled!==!1}function h(t,e){if(!Je(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 s=r.input();if(s!=null){const i=lt(s);i!=null&&(n[o]=i)}continue}if(typeof r=="object"&&"output"in r&&typeof r.output=="function"){if(t?.recordOutputs===!1)continue;const s=r.output();if(s!=null){const i=lt(s);i!=null&&(n[o]=i)}continue}const a=lt(r);a!=null&&(n[o]=a)}return n}var Le={usage:!1,providerMetadata:!1,embedding:!1,reranking:!1,runtimeContext:!1,headers:!1,toolChoice:!1,schema:!1};function Ue(t){var e,n,o,r,a,s,i,u;return{...Le,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:(s=t.headers)!=null?s:!1,toolChoice:(i=t.toolChoice)!=null?i:!1,schema:(u=t.schema)!=null?u:!1}}function Fe(t){const e={};for(const[n,o]of Object.entries(t??{}))Dt(e,`ai.settings.context.${n}`,o);return e}function Dt(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))Dt(t,`${e}.${o}`,r)}}function ut(t){return Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!=null).map(([e,n])=>[`ai.request.headers.${e}`,n]))}function V(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 S(t,e,n){const o={};for(const[r,a]of Object.entries(n))!e[r]||a==null||Object.assign(o,h(t,a));return o}function pt(t){return t==null?void 0:t/1e3}function Ke(t){var e;return{"gen_ai.client.operation.duration":pt(t.responseTimeMs),"gen_ai.client.operation.time_to_first_chunk":pt(t.timeToFirstOutputMs),"gen_ai.client.operation.time_per_output_chunk":pt((e=t.timeBetweenOutputChunksMs)==null?void 0:e.avg)}}var Be=class{constructor(t={}){this.callStates=new Map;var e;this.tracer=(e=t.tracer)!=null?e:v.getTracer("gen_ai"),this.supplementalAttributes=Ue(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 s;try{s=(a=this.enrichSpan)==null?void 0:a.call(this,{spanType:e,operationId:n,callId:o,runtimeContext:r})}catch{s=void 0}return{...We(s),...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():T.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():T.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=R(t.provider),a=Rt(t.operationId),s=t.runtimeContext,i=S(n,this.supplementalAttributes,{runtimeContext:Fe(s),headers:ut(t.headers)}),u=h(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(jt(t.instructions))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(vt({prompt:void 0,messages:t.messages}))},...i}),d=`${a} ${t.modelId}`,c=this.tracer.startSpan(d,{attributes:this.getSpanAttributes({attributes:u,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:s}),kind:x.INTERNAL}),p=v.setSpan(T.active(),c);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:c,rootContext:p,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:s,baseSupplementalAttributes:i})}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=R(t.provider),a=Rt(t.operationId),s=S(n,this.supplementalAttributes,{headers:ut(t.headers)}),i=h(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(jt(t.system))}:void 0,"gen_ai.input.messages":{input:()=>JSON.stringify(vt({prompt:t.prompt,messages:t.messages}))},...s,...S(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}})}),u=`${a} ${t.modelId}`,d=this.tracer.startSpan(u,{attributes:this.getSpanAttributes({attributes:i,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:x.INTERNAL}),c=v.setSpan(T.active(),d);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:n,rootSpan:d,rootContext:c,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:s})}onObjectStepStart(t){var e;const n=this.getCallState(t.callId);if(!n?.rootSpan||!n.rootContext)return;const{telemetry:o}=n,r=R(t.provider),a=h(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(Pe(t.promptMessages)):void 0},...n.baseSupplementalAttributes}),s=`chat ${t.modelId}`;n.inferenceSpan=this.tracer.startSpan(s,{attributes:this.getSpanAttributes({attributes:a,spanType:"languageModel",operationId:n.operationId,callId:t.callId,runtimeContext:n.runtimeContext}),kind:x.CLIENT},n.rootContext),n.inferenceContext=v.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(h(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($t({objectText:t.objectText,finishReason:t.finishReason}))}catch{return t.objectText}}},...S(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:V(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=R(t.provider),o=S(e,this.supplementalAttributes,{headers:ut(t.headers)}),r=t.value,a=t.operationId==="ai.embedMany",s=h(e,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...S(e,this.supplementalAttributes,{embedding:a?{"ai.values":{input:()=>r.map(c=>JSON.stringify(c))}}:{"ai.value":{input:()=>JSON.stringify(r)}}})}),i=`embeddings ${t.modelId}`,u=this.tracer.startSpan(i,{attributes:this.getSpanAttributes({attributes:s,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:x.CLIENT}),d=v.setSpan(T.active(),u);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:u,rootContext:d,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=h(n,{"gen_ai.operation.name":"agent_step",...e.baseSupplementalAttributes,...S(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:x.INTERNAL},e.rootContext),e.stepContext=v.setSpan(e.rootContext,e.stepSpan)}onLanguageModelCallStart(t){var e;const n=this.getCallState(t.callId);if(!n?.stepContext)return;const{telemetry:o}=n,r=R(t.provider),a=h(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 s=vt({prompt:void 0,messages:t.messages});return s.length>0?JSON.stringify(s):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:x.CLIENT},n.stepContext),n.inferenceContext=v.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(h(r,{...Ke(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(Nt({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}))},...S(r,this.supplementalAttributes,{usage:V(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=h(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}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"tool",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:x.INTERNAL},e.stepContext),i=v.setSpan(e.stepContext,s);e.toolSpans.set(o.toolCallId,{span:s,context:i})}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(h(r,{"gen_ai.execute_tool.duration":pt(t.toolExecutionMs)})),a.type==="tool-result")try{o.setAttributes(h(r,{"gen_ai.tool.call.result":{output:()=>JSON.stringify(a.output)}}))}catch{}else U(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(S(n,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:V(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(h(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(Nt({text:(a=t.text)!=null?a:void 0,reasoning:t.finalStep.reasoning,toolCalls:t.toolCalls,files:t.files,finishReason:t.finishReason}))}},...S(r,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.finalStep.providerMetadata?JSON.stringify(t.finalStep.providerMetadata):void 0},usage:V(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(h(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($t({objectText:JSON.stringify(t.object),finishReason:t.finishReason})):void 0},...S(o,this.supplementalAttributes,{providerMetadata:{"ai.response.providerMetadata":t.providerMetadata?JSON.stringify(t.providerMetadata):void 0},usage:V(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(h(n,{"gen_ai.usage.input_tokens":t.usage.tokens,...S(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=R(e.provider),r=h(n,{"gen_ai.operation.name":"embeddings","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...S(n,this.supplementalAttributes,{embedding:{"ai.values":{input:()=>t.values.map(u=>JSON.stringify(u))}}})}),a=`embeddings ${e.modelId}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"embedding",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:x.CLIENT},e.rootContext),i=v.setSpan(e.rootContext,s);e.embedSpans.set(t.embedCallId,{span:s,context:i})}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(h(r,{"gen_ai.usage.input_tokens":t.usage.tokens,...S(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=R(t.provider),o=S(e,this.supplementalAttributes,{headers:ut(t.headers)}),r=h(e,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":n,"gen_ai.request.model":t.modelId,...o,...S(e,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(u=>JSON.stringify(u))}}})}),a=`rerank ${t.modelId}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"operation",operationId:t.operationId,callId:t.callId,runtimeContext:void 0}),kind:x.CLIENT}),i=v.setSpan(T.active(),s);this.callStates.set(t.callId,{operationId:t.operationId,telemetry:e,rootSpan:s,rootContext:i,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=R(e.provider),r=h(n,{"gen_ai.operation.name":"rerank","gen_ai.provider.name":o,"gen_ai.request.model":e.modelId,...e.baseSupplementalAttributes,...S(n,this.supplementalAttributes,{reranking:{"ai.documents":{input:()=>t.documents.map(u=>JSON.stringify(u))}}})}),a=`rerank ${e.modelId}`,s=this.tracer.startSpan(a,{attributes:this.getSpanAttributes({attributes:r,spanType:"reranking",operationId:e.operationId,callId:t.callId,runtimeContext:e.runtimeContext}),kind:x.CLIENT},e.rootContext),i=v.setSpan(e.rootContext,s);e.rerankSpan={span:s,context:i}}onRerankEnd(t){const e=this.getCallState(t.callId);if(!e?.rerankSpan)return;const{span:n}=e.rerankSpan,{telemetry:o}=e;n.setAttributes(S(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())U(a,r),a.end();o.toolSpans.clear(),o.inferenceSpan&&(U(o.inferenceSpan,r),o.inferenceSpan.end(),o.inferenceSpan=void 0,o.inferenceContext=void 0),o.stepSpan&&(U(o.stepSpan,r),o.stepSpan.end(),o.stepSpan=void 0,o.stepContext=void 0);for(const{span:a}of o.embedSpans.values())U(a,r),a.end();o.embedSpans.clear(),o.rerankSpan&&(U(o.rerankSpan.span,r),o.rerankSpan.span.end(),o.rerankSpan=void 0),U(o.rootSpan,r),o.rootSpan.end(),this.cleanupCallState(n.callId)}};function ze(t){return ue({messages:t,emptyMessages:"remove",reasoning:"none",toolCalls:`before-last-${Gt}-messages`})}function Qe(t){return typeof t=="object"&&t!==null&&"role"in t&&"content"in t}function Ge(t){return Array.isArray(t)&&t.every(Qe)}function He(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,...rt("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,...r()}])},onToolExecutionEnd:a=>{const s=a.toolOutput.type==="tool-error";t("com.redocly.aiChat.toolCallFinished",[{conversation_id:e,...rt("toolCall",a.toolCall.toolCallId,"ai"),tool_name:a.toolCall.toolName,input:a.toolCall.input,step_number:o,success:!s,duration_ms:a.toolExecutionMs,...r(),...s&&{error:a.toolOutput.error instanceof Error?a.toolOutput.error.message:String(a.toolOutput.error)}}])},onStart:a=>{o=0,t("com.redocly.aiChat.conversationStarted",[{...rt("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 s=a.usage;t("com.redocly.aiChat.conversationFinished",[{...rt("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:s.inputTokens,output_tokens:s.outputTokens,total_tokens:s.totalTokens}])}}}function Ve(t,e){const n=()=>v.getSpan(T.active())?T.active():e;return{startSpan:(o,r,a)=>t.startSpan(o,r,a??e),startActiveSpan:((o,r,a,s)=>{if(typeof r=="function")return t.startActiveSpan(o,{},n(),r);if(typeof a=="function")return t.startActiveSpan(o,r,n(),a);if(s)return t.startActiveSpan(o,r,a,s);throw new Error("withParentContext: invalid startActiveSpan invocation")})}}const Ye=`You are a helpful assistant that can generate titles for conversations.
|
|
2
|
+
|
|
3
|
+
## Rules
|
|
4
|
+
- Titles should be at most 30 characters.
|
|
5
|
+
- No quotes, emojis, or trailing punctuation.
|
|
6
|
+
- No filler phrases like "Help with", "Question about", "How to".
|
|
7
|
+
- Prefer nouns or direct phrases.
|
|
8
|
+
- Be specific, not generic.
|
|
9
|
+
- Do not capitalize every word.
|
|
10
|
+
- If the message is long, extract the core intent and ignore extra details.
|
|
11
|
+
|
|
12
|
+
## Task
|
|
13
|
+
Generate a title for the conversation.
|
|
14
|
+
|
|
15
|
+
## Output format
|
|
16
|
+
Return only the title.
|
|
17
|
+
`,Xe=`You are on the final allowed step for this turn.
|
|
18
|
+
|
|
19
|
+
- Do not start new work.
|
|
20
|
+
- Do not call tools, except one short follow-up only if strictly required for safety.
|
|
21
|
+
- Do not offload in-scope Replay work to me or suggest manual fallback steps.
|
|
22
|
+
- If blocked, ask only for the exact missing input/permission needed to continue.
|
|
23
|
+
|
|
24
|
+
Reply with a concise wrap-up:
|
|
25
|
+
- Always state what you completed.
|
|
26
|
+
- Mention what remains only if there is unfinished work.
|
|
27
|
+
- Mention an unblocker only if you are actually blocked and need something specific from me.`;class Ze{model;tools;toolLoopAgent;maxSteps;context=[];systemInstructions=pe();getActiveStateMessage;constructor(e){const{activeConversationId:n,onFinish:o,onStepFinish:r,tools:a}=e;this.maxSteps=e.maxSteps??Ht,this.getActiveStateMessage=e.getActiveStateMessage,this.model=this.createModel(e.model);const s=({stepNumber:d,messages:c})=>{const p=[],m=this.buildActiveStateMessage();return m&&p.push({role:"user",content:m}),d===this.maxSteps-1&&p.push({role:"user",content:Xe}),p.length===0?void 0:{messages:[...c,...p]}},i=d=>{const c=d.messages?this.prepareMessages(d.messages):void 0,p=d.prompt?this.preparePrompt(d.prompt):void 0;return{...d,model:this.model,messages:c,prompt:p,instructions:[...this.systemInstructions,...this.context],tools:this.tools??d.tools}},u=new Be({...e.parentCtx&&{tracer:Ve(v.getTracer("ai"),e.parentCtx)}});this.toolLoopAgent=new ce({model:this.model,tools:a,stopWhen:de(this.maxSteps),onStepFinish:r,onFinish:o,maxOutputTokens:e.maxOutputTokens,maxRetries:e.maxRetries??Vt,prepareStep:s,prepareCall:i,telemetry:{isEnabled:!0,recordInputs:!0,recordOutputs:!0,functionId:"replay-ai-chat",integrations:[u,He(e.sendEvent,{conversationId:n,getModel:()=>({provider:this.model.provider,modelId:this.model.modelId})})]}})}createModel(e){return me(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 ge({model:this.model,system:Ye,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 ze(e)}preparePrompt(e){return Ge(e)?this.prepareMessages(e):e}}class tn{handlers=new Map;middlewares;constructor(e){this.middlewares=e?.middlewares??[]}register(e){this.handlers.set(e.name,e)}getToolSet(){const e={};for(const[n,o]of this.handlers)e[n]=this.buildTool(o);return e}buildTool(e){return{...e.definition,execute:this.wrapExecutor(e)}}wrapExecutor(e){const n=(r,a)=>({isError:!0,error:{message:r,details:a}}),o=this.applyMiddlewares(e.name,e.execute);return(r,a)=>{if(a.abortSignal?.aborted)return n("Tool execution was aborted.");try{const s=o(r,a);return typeof s=="object"&&s!==null&&"then"in s?s.then(i=>i,i=>n(i instanceof Error?i.message:"Unknown tool execution error")):s}catch(s){return n(s instanceof Error?s.message:"Unknown tool execution error")}}}applyMiddlewares(e,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((o,r)=>r(e,o),n)}}function Wt(){const t=mt();return gt({async mutationFn(e){const n=Ot(e);await ft.getInstance().upsert(n)},onSuccess(){t.invalidateQueries({queryKey:A.all()})},onError(e){console.error("Failed to upsert ai chat item:",e)}})}function en(t){const e=mt(),n=A.detailTitle(t??"");return gt({mutationKey:n,async mutationFn(o){if(e.isMutating({mutationKey:n,exact:!0})>1)return;const r=Ot(o);await ft.getInstance().upsert(r)},onSuccess(){e.invalidateQueries({queryKey:A.all()})},onError(o){console.error("Failed to upsert ai chat item:",o)}})}function nn(){const t=mt();return gt({async mutationFn(e){await ft.getInstance().remove(e)},onMutate:async e=>{await t.cancelQueries({queryKey:A.all()});const n=t.getQueryData(A.all());n&&t.setQueryData(A.all(),n.filter(o=>o.id!==e)),t.setQueryData(A.detail(e),null),t.setQueriesData({queryKey:A.infiniteHistories()},o=>o&&{...o,pages:o.pages.map(r=>({...r,items:r.items.filter(a=>a.id!==e)}))})},onError(e){console.error("Failed to remove ai chat:",e)},onSettled(){t.invalidateQueries({queryKey:A.all()})}})}var bt,Jt;function on(){if(Jt)return bt;Jt=1;function t(e,n){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let o,r=0;return function(...a){clearTimeout(o);const s=Date.now(),i=s-r,u=n-i;u<=0?(r=s,e.apply(this,a)):o=setTimeout(()=>{r=Date.now(),e.apply(this,a)},u)}}return bt=t,bt}var an=on();const rn=Qt(an);var Lt=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},g=(t,e,n)=>(Lt(t,e,"read from private field"),n?n.call(t):e.get(t)),_=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},q=(t,e,n,o)=>(Lt(t,e,"write to private field"),e.set(t,n),n);function sn(t,e){return e!=null?rn(t,e):t}var I,ct,dt,Y,X,Z,B,It,kt,ln=class{constructor(t=[]){_(this,I,void 0),_(this,ct,"ready"),_(this,dt,void 0),_(this,Y,new Set),_(this,X,new Set),_(this,Z,new Set),this.pushMessage=e=>{q(this,I,g(this,I).concat(e)),g(this,B).call(this)},this.popMessage=()=>{q(this,I,g(this,I).slice(0,-1)),g(this,B).call(this)},this.replaceMessage=(e,n)=>{q(this,I,[...g(this,I).slice(0,e),this.snapshot(n),...g(this,I).slice(e+1)]),g(this,B).call(this)},this.snapshot=e=>structuredClone(e),this["~registerMessagesCallback"]=(e,n)=>{const o=n?sn(e,n):e;return g(this,Y).add(o),()=>{g(this,Y).delete(o)}},this["~registerStatusCallback"]=e=>(g(this,X).add(e),()=>{g(this,X).delete(e)}),this["~registerErrorCallback"]=e=>(g(this,Z).add(e),()=>{g(this,Z).delete(e)}),_(this,B,()=>{g(this,Y).forEach(e=>e())}),_(this,It,()=>{g(this,X).forEach(e=>e())}),_(this,kt,()=>{g(this,Z).forEach(e=>e())}),q(this,I,t)}get status(){return g(this,ct)}set status(t){q(this,ct,t),g(this,It).call(this)}get error(){return g(this,dt)}set error(t){q(this,dt,t),g(this,kt).call(this)}get messages(){return g(this,I)}set messages(t){q(this,I,[...t]),g(this,B).call(this)}};I=new WeakMap,ct=new WeakMap,dt=new WeakMap,Y=new WeakMap,X=new WeakMap,Z=new WeakMap,B=new WeakMap,It=new WeakMap,kt=new WeakMap;var z,Ut=class extends fe{constructor({messages:t,...e}){const n=new ln(t);super({...e,state:n}),_(this,z,void 0),this["~registerMessagesCallback"]=(o,r)=>g(this,z)["~registerMessagesCallback"](o,r),this["~registerStatusCallback"]=o=>g(this,z)["~registerStatusCallback"](o),this["~registerErrorCallback"]=o=>g(this,z)["~registerErrorCallback"](o),q(this,z,n)}};z=new WeakMap;function un({experimental_throttle:t,resume:e=!1,...n}={}){const o=l.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(o.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const r={...n,onToolCall:p=>{var m,f;return(f=(m=o.current).onToolCall)==null?void 0:f.call(m,p)},onData:p=>{var m,f;return(f=(m=o.current).onData)==null?void 0:f.call(m,p)},onFinish:p=>{var m,f;return(f=(m=o.current).onFinish)==null?void 0:f.call(m,p)},onError:p=>{var m,f;return(f=(m=o.current).onError)==null?void 0:f.call(m,p)},sendAutomaticallyWhen:p=>{var m,f,k;return(k=(f=(m=o.current).sendAutomaticallyWhen)==null?void 0:f.call(m,p))!=null?k:!1}},a=l.useRef("chat"in n?n.chat:new Ut(r));("chat"in n&&n.chat!==a.current||"id"in n&&n.id!=null&&a.current.id!==n.id)&&(a.current="chat"in n?n.chat:new Ut(r));const s=l.useCallback(p=>a.current["~registerMessagesCallback"](p,t),[t,a.current.id]),i=l.useSyncExternalStore(s,()=>a.current.messages,()=>a.current.messages),u=l.useSyncExternalStore(a.current["~registerStatusCallback"],()=>a.current.status,()=>a.current.status),d=l.useSyncExternalStore(a.current["~registerErrorCallback"],()=>a.current.error,()=>a.current.error),c=l.useCallback(p=>{typeof p=="function"&&(p=p(a.current.messages)),a.current.messages=p},[a]);return l.useEffect(()=>{e&&a.current.resumeStream()},[e,a]),{id:a.current.id,messages:i,setMessages:c,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:d,resumeStream:a.current.resumeStream,status:u,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}const pn=20;function cn(t){if(t.length===0)return"No OpenAPI specs loaded.";const e=t.slice(0,pn),n=e.map(dn),o=t.length-e.length;return o>0&&n.push(` \u2026and ${o} more API(s) not shown.`),[`Loaded APIs (${t.length}):`,...n].join(`
|
|
28
|
+
`)}function dn(t){return[` apiId="${t.apiId}"`,`title="${t.title}"`,t.version?`version="${t.version}"`:null,t.primaryServer?`server="${t.primaryServer}"`:null].filter(Boolean).join(" ")}const mn=30;function gn(t){if(t.length===0)return"No Arazzo collections loaded.";const e=[`Arazzo collections (${t.length}):`];let n=mn,o=0,r=0;for(const s of t){if(n<=0){o+=s.workflows.length,r++;continue}if(e.push(fn(s)),n--,s.workflows.length===0)e.push(" (no workflows)");else if(n>=2){e.push(` workflows (${s.workflows.length}):`),n--;for(const i of s.workflows)n>0?(e.push(` ${hn(i)}`),n--):o++}else o+=s.workflows.length}const a=[o>0?`${o} more workflow(s)`:null,r>0?`${r} more collection(s)`:null].filter(Boolean);return a.length>0&&e.push(` \u2026and ${a.join(", plus ")} not shown.`),e.join(`
|
|
29
|
+
`)}function fn(t){const e=t.sourceApiIds.length>0?` apis=[${t.sourceApiIds.join(", ")}]`:"";return` collectionId="${t.collectionId}" title="${t.title}"${e}`}function hn(t){const e=`id="${t.workflowId}"`,n=t.summary?`label="${t.summary}"`:null,o=`[${t.stepCount} step${t.stepCount!==1?"s":""}]`;return[e,n,o].filter(Boolean).join(" ")}const yn=20;function Sn(t){if(t.length===0)return"No environments configured.";const e=t.slice(0,yn),n=e.map(vn),o=t.length-e.length;return o>0&&n.push(` \u2026and ${o} more environment(s) not shown.`),[`Environments (${t.length}); * marks the active environment:`,...n].join(`
|
|
30
|
+
`)}function vn(t){return[`${t.isActive?"*":" "} name="${t.name}"`,`inputs=${t.inputCount}`,`servers=${t.serverCount}`].join(" ")}const bn=30;function In(t){if(t.length===0)return"No tabs are open.";const e=t.slice(0,bn),n=e.map(kn),o=t.length-e.length;return o>0&&n.push(` \u2026and ${o} more tab(s) not shown.`),[`Open tabs (${t.length}), listed by tabIndex; * marks the active (focused) tab:`,...n].join(`
|
|
31
|
+
`)}function kn(t){const e=[t.collectionId?`collectionId="${t.collectionId}"`:null,t.workflowId?`workflowId="${t.workflowId}"`:null,t.stepId?`stepId="${t.stepId}"`:null,t.operationId?`operationId="${t.operationId}"`:null].filter(Boolean),n=[t.isPreview?"preview":null,t.isDraft?"draft":null,t.isHistory?"history":null].filter(Boolean);return[`${t.isActive?"*":" "} ${t.tabIndex}.`,`type="${t.type}"`,`label="${t.label}"`,...e,n.length>0?`(${n.join(", ")})`:null].filter(Boolean).join(" ")}const Cn="Auto-attached snapshot of the user's current Replay UI state. Generated by Replay before each step; not written by the user. It is a shallow summary \u2014 use tools to read detailed tab contents when needed.";function xn(t){const e=`
|
|
32
|
+
`.repeat(2),n=[Cn,e,In(t.tabs),e,cn(t.apis),e,gn(t.collections),e,Sn(t.environments)].join("");return he("active_state",n)}function _n(t){return t.apis.get({noproxy:!0}).map(wn)}function wn(t){return{apiId:t.id,title:t.info?.title??"Untitled API",version:t.info?.version,primaryServer:t.servers?.[0]?.url}}function Tn(t){return t.collections.get({noproxy:!0}).map(An)}function An(t){const e=(t.workflows??[]).map(o=>({workflowId:o.workflowId,summary:o.summary,stepCount:o.steps?.length??0})),n=(t.sourceDescriptions??[]).map(o=>o.apiId).filter(Boolean);return{collectionId:t.id,title:t.info?.title??"Untitled Collection",workflows:e,sourceApiIds:n}}function Mn(t){const e=t.environments.get({noproxy:!0}),n=t.activeEnvironmentId.get({noproxy:!0});return e.filter(o=>o.state!==Yt.Draft).map(o=>({name:o.name,isActive:o.name===n,inputCount:o.inputs.length,serverCount:o.servers.length}))}function On(t){const e=t.tabsState.tabs.get({noproxy:!0}),n=t.tabsState.activeTabIdx.get({noproxy:!0});return e.map((o,r)=>En(t,o,r,r===n))}function En(t,e,n,o){const r={tabIndex:n,type:e.data.type,isActive:o,isPreview:e.state===Xt.Preview};switch(e.data.type){case E.Collection:{const{collectionId:a}=e.data;return{...r,label:Rn(t,a)??a,collectionId:a}}case E.Workflow:{const{collectionId:a,workflowId:s}=e.data;return{...r,label:s,collectionId:a,workflowId:s}}case E.WorkflowRun:{const{collectionId:a,workflowId:s,historyId:i,label:u}=e.data;return{...r,label:u??`${s} run`,collectionId:a,workflowId:s,isHistory:i!=null}}case E.Step:{const a=e.data;return{...r,label:jn(a),collectionId:a.collectionId,workflowId:a.workflowId,stepId:a.stepId,operationId:a.draftStep?.operation?.operationId??null,isDraft:!a.collectionId&&!a.workflowId,isHistory:a.historyId!=null}}}}function Rn(t,e){return t.collections.find(n=>n.id.get()===e)?.info.title.get()}function jn(t){if(t.stepId)return t.stepId;if(t.draftStep){const e=[Zt(t.draftStep),te(t.draftStep)].filter(Boolean).join(" ");if(e)return e}return"New Request"}function qn(t){return{tabs:On(t),apis:_n(t),collections:Tn(t),environments:Mn(t)}}function Nn(){const{getCollection:t}=wt(),{getWorkflow:e}=ee(),{getStep:n}=ne(),{tab:o}=oe(),r=o?.data.get();return l.useMemo(()=>{if(!r)return null;switch(r.type){case E.Collection:const a=t(r.collectionId);return{...r,collection:a?a.get():null};case E.Workflow:const s=e({collectionId:r.collectionId,workflowId:r.workflowId});return{...r,workflow:s?s.get():null};case E.Step:const i=n({collectionId:r.collectionId,workflowId:r.workflowId,stepId:r.stepId});return{...r,step:i?i.get():null};case E.WorkflowRun:const u=e({collectionId:r.collectionId,workflowId:r.workflowId});return{...r,workflow:u?u.get():null}}},[r,t,e,n])}function $n(t){if(!t||typeof t!="object"||!("changes"in t)||!Array.isArray(t.changes))return t;const e=t.changes.filter(o=>o&&typeof o=="object"&&"approved"in o&&o.approved===!0),n="meta"in t&&typeof t.meta=="object"?t.meta:{};return{...t,changes:e,meta:{...n,totalChanges:t.changes.length,approvedChanges:e.length}}}function Pn(){return(t,e)=>(n,o)=>e($n(n),o)}function Dn(){const{getApiOperation:t}=ae(),e=Tt();return l.useMemo(()=>({getApiOperation:t,...e}),[t,e])}function Wn(t){const{convertOperationToReplayValue:e}=st(),n=Nn(),o=Dn(),r=ht(),a=At(),{attachApiToCollection:s}=wt(),{handleCloseByDataId:i}=Tt(),u=l.useRef(n);return u.current=n,{tools:l.useMemo(()=>{const d=new tn({middlewares:[Pn()]});return ye(d,{[Ae.name]:void 0,[Te.name]:{store:a,settingsState:r},[we.name]:{store:a},[_e.name]:{store:a},[xe.name]:{store:a,attachApiToCollection:s,handleCloseByDataId:i,convertOperationToReplayValue:e},[Ce.name]:{store:a},[ke.name]:{model:t},[Ie.name]:{store:a},[be.name]:{store:a,context:o},[ve.name]:{getActiveTabDetailedData:()=>u.current},[Se.name]:{store:a}}),d.getToolSet()},[s,e,i,t,o,r,a])}}function Jn(t){const{children:e,chatId:n,model:o,initialMessages:r,onChatFinish:a,onChatMessagesUpdated:s}=t,i=ht(),{getReuniteAuth:u}=st(),{tools:d}=Wn(o),{sendEvent:c}=re(),p=l.useRef(d),m=l.useRef(o),{isOpen:f,openPanel:k,closePanel:tt}=Mt(),N=l.useRef(void 0),Q=At(),w=l.useRef(Q);p.current=d,m.current=o,w.current=Q;const b=l.useMemo(()=>{N.current?.end();const O=v.getTracer("replay-ai-chat").startSpan("ai.chat.session",{attributes:{conversation_id:n}});N.current=O;const L=v.setSpan(T.active(),O);return new Ze({activeConversationId:n,model:m.current,tools:p.current,sendEvent:c,parentCtx:L,getActiveStateMessage:()=>xn(qn(w.current))})},[n,c]);l.useEffect(()=>()=>N.current?.end(),[]);const F=l.useMemo(()=>{if(b)return new Me({agent:b.getAgent()})},[b]);l.useEffect(()=>{b.setModel(o)},[b,o]),l.useEffect(()=>{b.registerTools(d)},[b,d]);const{messages:M,setMessages:$,sendMessage:G,status:P,error:et,stop:D,addToolApprovalResponse:W}=un({id:n,messages:r,transport:F,sendAutomaticallyWhen:je,onFinish(O){!a||!b||a({agentLoop:b,chat:this},O)}}),J=l.useMemo(()=>P==="streaming"||P==="submitted",[P]),H=l.useCallback(()=>{i.aiEnabled.get()===!0&&k()},[k,i.aiEnabled]),nt=l.useCallback(()=>{tt()},[tt]),y=l.useCallback(async O=>{const L=O.trim();if(!(!L||!F)){if(o.provider===it){const C=await u?.();C?.baseUrl&&C?.accessToken&&b.setModel({provider:it,baseUrl:C.baseUrl,accessToken:C.accessToken})}$(C=>Oe(C)?Ee(C):C),G({text:L})}},[b,u,o.provider,G,$,F]),K=l.useCallback(()=>{J&&D()},[J,D]);l.useEffect(()=>()=>{D()},[n,D]);const Ct=l.useCallback(O=>{const L=O(M),C=L.map(ot=>ot.message),xt=[...M];for(const ot of L)xt[ot.index]=ot.message;$(xt),s?.(C)},[M,s,$]),Bt=l.useMemo(()=>({messages:M,isStreaming:J,chatStatus:P,chatError:et,sendMessage:y,updateMessages:Ct,stopGeneration:K,addToolApprovalResponse:W}),[W,et,J,M,y,P,K,Ct]),zt=l.useMemo(()=>({isOpen:f,openPanel:H,closePanel:nt}),[f,H,nt]);return at.jsx(Re.Provider,{value:Bt,children:at.jsx(se.Provider,{value:zt,children:e})})}function Ln(t){return t.slice(-2)}function Un(t,e){return!!(t||e<1)}function Fn(t){return l.useCallback(async(e,n)=>{if(Un(t,n.messages.length))return null;const o=n.messages[0],r=qe(o.parts);try{return(await e.agentLoop.generateTitle(r)).trim()}catch(a){return console.error("Unable to generate chat title",a),null}},[t])}function Kn({chatId:t,model:e,existingTitle:n}){const{mutate:o}=en(t),r=Fn(n);return l.useCallback(async(...a)=>{const s=await r(...a);s!==null&&s.length!==0&&o({id:t,model:e,messages:[],title:s})},[r,e,t,o])}function Bn({chatId:t,model:e}){const{mutate:n}=Wt();return l.useCallback((o,r)=>{const a=Ln(r.messages);n({id:t,model:e,messages:a})},[e,t,n])}function zn({chatId:t,model:e}){const{mutate:n}=Wt();return l.useCallback(o=>{o.length!==0&&n({id:t,model:e,messages:o})},[e,t,n])}function Qn(t){return l.useMemo(()=>{const e=[yt];if(t){for(const[n,o]of Object.entries(t))if(o.enabled&&o.apiKey){const r=o.models.map(a=>({...a,provider:n}));e.push(...r)}}return e},[t])}function Ft(t){return typeof t=="function"?t():t}function Kt(t,e){try{const n=globalThis.localStorage.getItem(t);return n===null?Ft(e):n}catch{return Ft(e)}}function Gn(t,e){try{globalThis.localStorage.setItem(t,e)}catch{console.error("Failed to write to localStorage",{key:t,value:e})}}function Hn(t,e){const[n,o]=l.useState(()=>Kt(t,e)),r=l.useRef(e);r.current=e,l.useEffect(()=>{o(Kt(t,r.current))},[t]);const a=l.useCallback(s=>{o(i=>{const u=s instanceof Function?s(i):s;return Gn(t,u),u})},[t]);return[n,a]}const Vn="replay:ai:selectedModelId";function Yn(t){const{availableModels:e,aiProviders:n,reuniteAuth:o}=t,[r,a]=Hn(Vn,yt.id);return l.useEffect(()=>{e.find(s=>s.id===r)||a(yt.id)},[e,r,a]),{model:l.useMemo(()=>{const s={provider:it,baseUrl:o.baseUrl,accessToken:o.accessToken},i=e.find(d=>d.id===r);if(!i||i.provider===it)return s;const u=n?.[i.provider];return!u||!u.apiKey||!u.enabled?s:{provider:i.provider,modelId:i.id,apiKey:u.apiKey}},[r,e,n,o]),selectedModelId:r,selectModel:a}}function Xn(){const[t,e]=l.useState({baseUrl:"",accessToken:""}),{getReuniteAuth:n}=st();return l.useEffect(()=>{let o=!1;async function r(){const a=await n?.();o||e({baseUrl:a?.baseUrl??"",accessToken:a?.accessToken??""})}return r().catch(()=>{o||e({baseUrl:"",accessToken:""})}),()=>{o=!0}},[n]),t}function Zn(t){const{children:e}=t,[n,o]=l.useState(Et),[r,a]=l.useState(n),[s,i]=l.useState(null),u=ht(),d=st(),{openPanel:c}=Mt(),p=r!==n,m=l.useCallback(()=>{const y=Et();a(y),o(y)},[]),f=l.useCallback(y=>{a(y)},[]),{data:k}=Ne(r),tt=Xn(),N=Qn(d.aiProviders),{selectedModelId:Q,model:w,selectModel:b}=Yn({availableModels:N,aiProviders:d.aiProviders,reuniteAuth:tt}),F=nn(),M=Bn({chatId:n,model:w}),$=zn({chatId:n,model:w}),G=Kn({chatId:n,model:w,existingTitle:k?.title}),P=l.useCallback((y,K)=>{K.isAbort||(M(y,K),G(y,K))},[M,G]),et=l.useCallback((...y)=>{$(...y)},[$]),D=l.useCallback(y=>{(r===y||n===y)&&m(),F.mutate(y)},[m,n,F,r]),W=k?.id;l.useEffect(()=>{W&&W!==n&&o(W)},[W,r,n]);const J=l.useCallback(()=>{i(null)},[]),H=l.useCallback(y=>{u.aiEnabled.get()&&(m(),i(y),c())},[c,m,u.aiEnabled]),nt=l.useMemo(()=>({chatId:n,model:w,availableModels:N,selectedModelId:Q,selectModel:b,onSettingsOpen:d.onSettingsOpen,title:k?.title??ie.title,isLoading:p,selectChat:f,removeChat:D,createNewChat:m,openAiChatWithPresetInput:H,pendingComposerPreset:s,clearPendingComposerPreset:J}),[n,N,k?.title,w,p,f,D,m,H,s,J,Q,b,d.onSettingsOpen]);return at.jsx(le.Provider,{value:nt,children:at.jsx(Jn,{chatId:n,model:w,initialMessages:k?.messages,onChatFinish:P,onChatMessagesUpdated:et,children:e})})}export{Zn as AiChatProvider};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as o,a as m,d as y}from"./redocly-openapi-docs.min.ai-chat-mappers-y6k4QA37.js";import{a as h,b as r,c as d}from"./redocly-openapi-docs.min.ai-message-parts.schema-C7fjQhYX.js";import{a as c,e as a,b as g}from"./redocly-openapi-docs.min.indexes-Bp4ld5gB.js";const u={orderBy:[c(r.createdAt),c(r.indexWithinInsertBatch)],with:{parts:{orderBy:[c(h.index)]}}};class b{constructor(t){this.sqliteDB=t}sqliteDB;async findAll(){return await this.initialize(),(await this.db.query.aiChats.findMany({with:{messages:u}})).map(o)}async findRecentChatsPage(t){await this.initialize();const i=t.limit+1,s=await this.db.query.aiChats.findMany({orderBy:(l,{desc:w})=>w(l.updatedAt),limit:i,offset:t.offset}),e=s.slice(0,t.limit),n=s.length>t.limit,f=t.offset+e.length;return{items:e.map(l=>{const w={...l,messages:[]};return o(w)}),hasMore:n,nextOffset:f}}async findOne(t){await this.initialize();const i=await this.db.query.aiChats.findFirst({where:a(d.id,t),with:{messages:u}});return i&&o(i)}async upsert(t){await this.initialize();const i=m(t);await this.db.query.aiChats.findFirst({where:a(d.id,i.id),columns:{id:!0}})?await this.db.update(d).set(i).where(a(d.id,i.id)):await this.db.insert(d).values(i);for(let s=0;s<t.messages.length;s++)await this.upsertMessageRowAndParts(t.id,s,t.messages[s])}async remove(t){await this.initialize(),await this.db.delete(d).where(a(d.id,t))}async upsertMessageRowAndParts(t,i,s){const e=await this.db.query.aiMessages.findFirst({where:g(a(r.aiChatId,t),a(r.uiId,s.id))}),n=y(t,i,s,e?.id);e?await this.db.update(r).set({...n,indexWithinInsertBatch:e.indexWithinInsertBatch}).where(a(r.id,e.id)):await this.db.insert(r).values(n),await this.db.delete(h).where(a(h.aiMessageId,n.id)),n.parts.length>0&&await this.db.insert(h).values(n.parts)}get db(){return this.sqliteDB.db}async initialize(){await this.sqliteDB.initialize()}}export{b as AiChatSqliteDBStorage};
|