@epam/statgpt-dial-toolkit 0.7.0-dev.3 → 0.7.0-dev.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs +3 -3
  2. package/index.mjs +550 -662
  3. package/package.json +4 -2
  4. package/LICENSE +0 -21
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",T=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${l}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${l}/deployments/${s}/configuration`,DATASETS_METADATA:s=>`/v1/deployments/${s}/route/metadata/datasets`,PYTHON_ATTACHMENT:s=>`/v1/deployments/${s}/route/python-attachment`,SHARE_CONVERSATION:`${T}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${T}/list`,SHARE_CONVERSATION_DISCARD:`${T}/discard`,SHARE_CONVERSATION_REVOKE:`${T}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},U={LENGTH:"length",STOP:"stop"},f={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},V={CONTENT_FILTER:"content_filter",500:"500"},x={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},F=[f.MINUTE,f.DAILY,f.WEEKLY,f.MONTHLY],K="statgpt",g={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var C=(s=>(s.CONVERSATION="CONVERSATION",s))(C||{}),y=(s=>(s.ME="me",s.OTHERS="others",s))(y||{}),$=(s=>(s.CSV="text/csv",s.TABLE="application/dial-ttyd-table",s.PLOTLY="application/vnd.plotly.v1+json",s.MARKDOWN="text/markdown",s.JSON="application/json",s.JPEG="image/jpeg",s.PNG="image/png",s.CROSS_DATASET_GRID="cross_dataset_grid",s.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s.CUSTOM_CODE_SAMPLE="custom_code_sample",s))($||{}),D=(s=>(s.LINK="link",s))(D||{});const j=s=>s.content?(console.info(`Using direct content format: ${s.content}`),s.content):s.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):s.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${s.choices[0].message.content}`),s.choices[0].message.content):(console.info("Unknown SSE data format:",s),null),v=(s,t,n)=>{if(t?.(s),n){const e=j(s);e&&n(e)}},w=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,k=(s,t)=>{const n=s?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},Y=(s,t)=>{const n=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&B(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=k(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function B(s,t){if(t.content){const n=G(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function G(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const J={CHAT:"/api/chat"},X="application/json",z="Content-Type",p="Api-Key",W="X-CONVERSATION-ID",O="Ocp-Apim-Subscription-Key";class N extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details,this.displayMessage=t.displayMessage}}const Q=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Z=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)Q(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},A=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[z]=t?.contentType||X),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[p]=s),t?.chatReference&&(e[W]=t.chatReference),{...e,...n}},ee=s=>{const t={...s};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[O]&&(t[O]=t[O].substring(0,8)+"...[REDACTED]"),t},te=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),L=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},b=s=>{const t=Date.now(),n=Z(s.name);return`${s.folderId}/${n}-${t}`},ne=s=>({resourceTypes:[C.CONVERSATION],with:s}),_=async(s,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(s,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function h(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function se(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function q(s){if(s?.kind!==g.RATE_LIMIT||typeof s.retryAfterSeconds!="number")return null;const t=new Date(s.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+s.retryAfterSeconds*1e3)}function re(s,t=Date.now()){const n=q(s);return n?n.getTime()>t:!1}function oe(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class M{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:o,onError:a,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,o),i?.()}catch(u){this.handleStreamError(u,a)}}async initializeStreamRequest(t,n,e,r){const o=A(void 0,{jwt:r}),a=await _(t,{Accept:"text/event-stream",...o},{method:"POST",body:n,signal:e});if(!a.ok){const i=await a.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new N({status:a.status,message:c.error??"No response body"})}if(!a.body)throw new N({message:"No response body",status:a.status});return a.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:o}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const a=this.decoder.decode(o,{stream:!0});e+=a;const i=e.split(`
2
- `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,n)}}finally{t.releaseLock()}}handleStreamError(t,n){const e=t instanceof Error?t:new Error(String(t));throw n?.(e),e}parseSSEDataLine(t,n){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let o;try{o=JSON.parse(r)}catch(a){console.error(`Failed to parse SSE data: ${r} ${a}`)}n?.(o)}}}const H=new M,ae=async(s,t,n,e,r)=>{const{onMessage:o,onToken:a,onComplete:i,onError:c,model:u,signal:R}=n,I={conversationId:s,messages:t,model:u,custom_fields:r};await H.streamChat(J.CHAT,I,{onMessage:P=>v(P,o,a),onComplete:i,onError:c,signal:R},e)},m=s=>s instanceof Error&&s.message.includes("404"),S=s=>`/v1/conversations/${h(s)}`;function E(s){console.warn("[ConversationApi] suppressed error, returning empty result",s)}class ie{constructor(t){this.client=t}async getConversations(t,n,e){const r=`${n?e?`${n}/${e}`:`${n}`:""}`,o=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(o+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=L(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(a){if(m(a))return E({endpoint:o,error:a}),[];throw a}}async getConversation(t,n){try{return await this.client.getRequest(S(t),n)}catch(e){if(m(e))return E({endpoint:S(t),error:e}),null;throw e}}async getFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async putOnboardingFile(t,n,e,r){try{const o=`${d.VERSION}/${h(n)}`,a="----NodeMultipartBoundary",c=[`--${a}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${a}--`,""].join(`\r
3
- `);return await this.client.request(o,r,{method:"PUT",body:c,headers:te(a),isFormData:!0})}catch(o){if(m(o))return E({filePath:n,error:o}),null;throw o}}async getOnboardingFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async getFileBlob(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async deleteFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(m(e)){E({filePath:t,error:e});return}throw e}}async putFile(t,n,e){try{const r=`${d.VERSION}/${h(t)}`,o=new FormData,a=decodeURIComponent(t.split("/").at(-1)??"file");o.append("attachment",n,a),await this.client.request(r,e,{method:"PUT",body:o,isFormData:!0})}catch(r){if(m(r)){E({filePath:t,error:r});return}throw r}}async createConversation(t,n){const e=t?.id||b(t),{name:r,folderId:o,model:a,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:o,model:a,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(S(e),n,{method:"PUT",body:u}),{id:e,name:r,folderId:o,model:a,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:n})}async getSharedConversations(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:n})}async revokeSharedConversations(t,n){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:n})}async updateConversation(t,n,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const o={...r,...n,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:o})}async deleteConversation(t,n,e){n?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:n?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,r=encodeURIComponent(e),o=`${d.CHAT(r)}?api-version=${this.client.config.version}`,a={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(o,n,{method:"POST",body:a,chatReference:t.conversationId})}async rateResponse(t,n,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:n,rate:e}})}async renameConversation(t,n,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:n,overwrite:!0}})}}class ce{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,n,e){return this.request(t,n,{...e,method:"GET"})}async postRequest(t,n,e){return this.request(t,n,{...e,method:"POST"})}async requestBlob(t,n,e){const r=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};try{return(await _(r,o,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:r,error:a instanceof Error?a.message:String(a)}),a}}async request(t,n,e){const r=Date.now(),o=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",o,e,a);try{const i=await _(o,a,e),c=Date.now()-r;let u;const R=await i.text();try{u=R?JSON.parse(R):{}}catch{if(this.addErrorRequestParsing(o,e,i,c,R),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${R.substring(0,100)}`);u={data:R}}if(!i.ok){this.addErrorRequestLog(o,e,i,c,u);const I=w(u,i);throw new Error(`API request failed: ${I}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:o,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const r=`${this.config.host}${t}`,o=A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},e.headers);this.addInfoRequestLog("Stream Request",r,e,o);const a=await _(r,o,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,status:a.status,statusText:a.statusText}),new Error(`Stream request failed: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("No response body for stream");return a.body}addInfoRequestLog(t,n,e,r){const o={method:e.method||"GET",url:n,headers:ee(r)};e.body&&(o.body=e.body),console.info(t,o)}addErrorRequestLog(t,n,e,r,o){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:o})}addErrorRequestParsing(t,n,e,r,o){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:o.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=$;exports.COMPLETION_FINISH_REASON=U;exports.CUSTOM_VIEW_STATE_KEY=K;exports.ChatStreamSSEClient=M;exports.ConversationApi=ie;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=V;exports.DIAL_ERROR_TYPES=x;exports.DialApiClient=ce;exports.ERROR_CONTEXT_KIND=g;exports.EXCEEDED_LIMIT=f;exports.EXCEEDED_LIMIT_ORDER=F;exports.InvitationType=D;exports.ResourceTypes=C;exports.ShareTarget=y;exports.chatStreamSSEClient=H;exports.decodeApiUrl=se;exports.encodeApiUrl=h;exports.formatDateTime=oe;exports.generateConversationId=b;exports.getErrorMessage=w;exports.getRateLimitRestoreDate=q;exports.getSharedConversationsRequest=ne;exports.handleStreamMessage=v;exports.isRateLimitStillActive=re;exports.mergeMessages=Y;exports.parseConversationName=L;exports.sendRequest=_;exports.streamChatResponse=ae;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@epam/statgpt-shared-toolkit");var t=`v1`,n=`/${t}/ops/resource/share`,r={VERSION:`/${t}`,BUCKET:`/${t}/bucket`,CONVERSATIONS:`/${t}/metadata/conversations`,CONVERSATION_BY_ID:e=>`/${t}/metadata/conversations/${e}`,CHAT:e=>`/openai/deployments/${e}/chat/completions`,MODELS:`/openai/models`,CONFIGURATION:e=>`/${t}/deployments/${e}/configuration`,DATASETS_METADATA:e=>`/v1/deployments/${e}/route/metadata/datasets`,PYTHON_ATTACHMENT:e=>`/v1/deployments/${e}/route/python-attachment`,SHARE_CONVERSATION:`${n}/create`,SHARE_CONVERSATION_ACCEPT:e=>`/${t}/invitations/${e}?accept=true`,SHARE_CONVERSATION_DETAILS:e=>`/${t}/invitations/${e}`,SHARE_CONVERSATION_LIST:`${n}/list`,SHARE_CONVERSATION_DISCARD:`${n}/discard`,SHARE_CONVERSATION_REVOKE:`${n}/revoke`,RATE:e=>`/${t}/${e}/rate`,RENAME:`/${t}/ops/resource/move`},i={LENGTH:`length`,STOP:`stop`},a={MINUTE:`minute`,DAILY:`daily`,WEEKLY:`weekly`,MONTHLY:`monthly`},o={CONTENT_FILTER:`content_filter`,500:`500`},s={RUNTIME_ERROR:`runtime_error`,RATE_LIMIT_EXCEEDED:`rate_limit_exceeded`},c=[a.MINUTE,a.DAILY,a.WEEKLY,a.MONTHLY],l=`statgpt`,u={RATE_LIMIT:`rate_limit`,UNKNOWN:`unknown`},d=function(e){return e.CONVERSATION=`CONVERSATION`,e}({}),f=function(e){return e.ME=`me`,e.OTHERS=`others`,e}({}),p=function(e){return e.CSV=`text/csv`,e.TABLE=`application/dial-ttyd-table`,e.PLOTLY=`application/vnd.plotly.v1+json`,e.MARKDOWN=`text/markdown`,e.JSON=`application/json`,e.JPEG=`image/jpeg`,e.PNG=`image/png`,e.CROSS_DATASET_GRID=`cross_dataset_grid`,e.CUSTOM_DATA_GRID=`custom_data_grid`,e.CUSTOM_CHART=`custom_chart`,e.CUSTOM_CODE_SAMPLE=`custom_code_sample`,e}({}),m=function(e){return e.LINK=`link`,e}({}),h=e=>e.content?(console.info(`Using direct content format: ${e.content}`),e.content):e.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${e.choices[0].delta.content}`),e.choices[0].delta.content):e.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${e.choices[0].message.content}`),e.choices[0].message.content):(console.info(`Unknown SSE data format:`,e),null),g=(e,t,n)=>{if(t?.(e),n){let t=h(e);t&&n(t)}},_=(e,t)=>e.error||e.message||`${t.status} ${t.statusText}`,v=(e,t)=>{let n=e?.reduce((e,t)=>(e[t.index]=t,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||``)+e.content),e.name&&(n[e.index].name=(n[e.index].name||``)+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},y=(e,t)=>{let n=structuredClone(e);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&b(n,e),e.custom_content&&(n.custom_content||={},e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=v(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function b(e,t){if(t.content){let n=x(t.content);n==null?e.content=`${e.content||``}${t.content}`:e.content=e.content.slice(0,-n)}}function x(e){let t=e.match(/delete_chars\((\d+)\)/);return t==null?null:parseInt(t[1],10)}var S=e=>{let t=e.name?.split(`__`)||[],n=t.length>1?t.slice(1).join(`__`):e.name;return{modelId:t[0],conversationName:n}},C=t=>{let n=Date.now(),r=(0,e.getClearedConversationName)(t.name);return`${t.folderId}/${r}-${n}`},w=e=>({resourceTypes:[d.CONVERSATION],with:e}),T=async(e,t,n)=>{let r=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(e,{method:n.method||`GET`,headers:t,body:r,signal:n?.signal})};function E(e){return e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}function D(e){return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}function O(e){if(e?.kind!==u.RATE_LIMIT||typeof e.retryAfterSeconds!=`number`)return null;let t=new Date(e.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+e.retryAfterSeconds*1e3)}function k(e,t=Date.now()){let n=O(e);return n?n.getTime()>t:!1}function A(e,t=`en-GB`){return{date:e.toLocaleDateString(t),time:e.toLocaleTimeString(t,{hour:`2-digit`,minute:`2-digit`})}}var j=class{constructor(){this.decoder=new TextDecoder}async streamChat(e,t,n={},r){let{onMessage:i,onError:a,onComplete:o,signal:s}=n;try{let n=await this.initializeStreamRequest(e,t,s,r);await this.processStreamData(n,i),o?.()}catch(e){this.handleStreamError(e,a)}}async initializeStreamRequest(t,n,r,i){let a=await T(t,{Accept:`text/event-stream`,...(0,e.getHeaders)(void 0,{jwt:i})},{method:`POST`,body:n,signal:r});if(!a.ok){let t=await a.text(),n={};try{n=JSON.parse(t)}catch{n.error=`Failed to parse error body`}throw new e.HttpError({status:a.status,message:n.error??`No response body`})}if(!a.body)throw new e.HttpError({message:`No response body`,status:a.status});return a.body.getReader()}async processStreamData(e,t){let n=``;try{for(;;){let{done:r,value:i}=await e.read();if(r){n.trim()&&this.parseSSEDataLine(n,t);break}let a=this.decoder.decode(i,{stream:!0});n+=a;let o=n.split(`
2
+ `);n=o.pop()||``;for(let e of o)this.parseSSEDataLine(e,t)}}finally{e.releaseLock()}}handleStreamError(e,t){let n=e instanceof Error?e:Error(String(e));throw t?.(n),n}parseSSEDataLine(e,t){let n=e.trim();if(!(!n||n.startsWith(`:`))&&n.startsWith(`data: `)){let e=n.slice(6);if(e===`[DONE]`){console.info(`SSE: Stream completed`);return}let r;try{r=JSON.parse(e)}catch(t){console.error(`Failed to parse SSE data: ${e} ${t}`)}t?.(r)}}},M=new j,N=async(t,n,r,i,a)=>{let{onMessage:o,onToken:s,onComplete:c,onError:l,model:u,signal:d}=r,f={conversationId:t,messages:n,model:u,custom_fields:a};await M.streamChat(e.API_ROUTES.CHAT,f,{onMessage:e=>g(e,o,s),onComplete:c,onError:l,signal:d},i)},P=e=>e instanceof Error&&e.message.includes(`404`),F=e=>`/v1/conversations/${E(e)}`;function I(e){console.warn(`[ConversationApi] suppressed error, returning empty result`,e)}var L=class{constructor(e){this.client=e}async getConversations(e,t,n){let i=`${t?n?`${t}/${n}`:`${t}`:``}`,a=`${r.CONVERSATIONS}/${i}`;try{return(await this.client.getRequest(a+`/?limit=1000&recursive=false`,e).then(e=>e.items||[])).map(e=>{let{conversationName:t,modelId:n}=S(e);return{id:e.url?.replace(`conversations/`,``)||e.name,name:t,folderId:i,createdAt:e.createdAt,updatedAt:e.updatedAt,model:{id:n,name:n}}})}catch(e){if(P(e))return I({endpoint:a,error:e}),[];throw e}}async getConversation(e,t){try{return await this.client.getRequest(F(e),t)}catch(t){if(P(t))return I({endpoint:F(e),error:t}),null;throw t}}async getFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.getRequest(n,t)}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async putOnboardingFile(t,n,i,a){try{let o=`${r.VERSION}/${E(n)}`,s=`----NodeMultipartBoundary`,c=[`--${s}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,`Content-Type: application/json`,``,JSON.stringify(i),`--${s}--`,``].join(`\r
3
+ `);return await this.client.request(o,a,{method:`PUT`,body:c,headers:(0,e.getMultipartHeaders)(s),isFormData:!0})}catch(e){if(P(e))return I({filePath:n,error:e}),null;throw e}}async getOnboardingFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.getRequest(n,t)}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async getFileBlob(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.requestBlob(n,t,{method:`GET`})}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async deleteFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;await this.client.request(n,t,{method:`DELETE`})}catch(t){if(P(t)){I({filePath:e,error:t});return}throw t}}async putFile(e,t,n){try{let i=`${r.VERSION}/${E(e)}`,a=new FormData,o=decodeURIComponent(e.split(`/`).at(-1)??`file`);a.append(`attachment`,t,o),await this.client.request(i,n,{method:`PUT`,body:a,isFormData:!0})}catch(t){if(P(t)){I({filePath:e,error:t});return}throw t}}async createConversation(e,t){let n=e?.id||C(e),{name:r,folderId:i,model:a,messages:o,custom_fields:s}=e,c={id:n,name:r,folderId:i,model:a,messages:o||[],selectedAddons:e.selectedAddons||[],prompt:e.prompt||``,temperature:e.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:s};return await this.client.request(F(n),t,{method:`PUT`,body:c}),{id:n,name:r,folderId:i,model:a,createdAt:c.createdAt,updatedAt:c.updatedAt}}async generateConversationLink(e,t){return await this.client.postRequest(r.SHARE_CONVERSATION,e,{body:t})}async getSharedConversations(e,t){return await this.client.postRequest(r.SHARE_CONVERSATION_LIST,e,{body:t})}async revokeSharedConversations(e,t){await this.client.postRequest(r.SHARE_CONVERSATION_REVOKE,e,{body:t})}async updateConversation(e,t,n){let r=await this.getConversation(e,n);if(!r)throw Error(`Conversation with id ${e} not found`);let i={...r,...t,updatedAt:Date.now()};return await this.client.request(F(e),n,{method:`PUT`,body:i})}async deleteConversation(e,t,n){t?.isShared?await this.client.postRequest(r.SHARE_CONVERSATION_DISCARD,n,{body:{resources:[{url:t?.url}]}}):await this.client.request(F(decodeURI(e)),n,{method:`DELETE`})}async streamChat(e,t){let n=e.model.id,i=encodeURIComponent(n),a=`${r.CHAT(i)}?api-version=${this.client.config.version}`,o={messages:e.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:e.custom_fields};return await this.client.stream(a,t,{method:`POST`,body:o,chatReference:e.conversationId})}async rateResponse(e,t,n,i){return await this.client.postRequest(r.RATE(e),i,{body:{responseId:t,rate:n}})}async renameConversation(e,t,n){return await this.client.postRequest(r.RENAME,n,{body:{sourceUrl:e,destinationUrl:t,overwrite:!0}})}},R=class{constructor(e){this.config=e,console.info(`DialApiClient initialized`,{host:e.host||`NOT SET`,hasApiKey:!!e.apiKey,version:e.version})}async getRequest(e,t,n){return this.request(e,t,{...n,method:`GET`})}async postRequest(e,t,n){return this.request(e,t,{...n,method:`POST`})}async requestBlob(t,n,r){let i=`${this.config.host}${t}`,a={...(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0}),...r.headers};try{return(await T(i,a,r)).blob()}catch(e){throw console.error(`API Request Exception`,{method:r.method,url:i,error:e instanceof Error?e.message:String(e)}),e}}async request(t,n,r){let i=Date.now(),a=`${this.config.host}${t}`,o={...(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0}),...r.headers};this.addInfoRequestLog(`API Request`,a,r,o);try{let e=await T(a,o,r),t=Date.now()-i,n,s=await e.text();try{n=s?JSON.parse(s):{}}catch{if(this.addErrorRequestParsing(a,r,e,t,s),!e.ok)throw Error(`API request failed: ${e.status} ${e.statusText} - ${s.substring(0,100)}`);n={data:s}}if(!e.ok){this.addErrorRequestLog(a,r,e,t,n);let i=_(n,e);throw Error(`API request failed: ${i}`)}return n}catch(e){let t=Date.now()-i;throw console.error(`API Request Exception`,{method:r.method,url:a,duration:`${t}ms`,error:e instanceof Error?e.message:String(e)}),e}}async stream(t,n,r){let i=`${this.config.host}${t}`,a=(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0},r.headers);this.addInfoRequestLog(`Stream Request`,i,r,a);let o=await T(i,a,r);if(!o.ok)throw console.error(`Stream Request Failed`,{method:r.method||`POST`,url:i,status:o.status,statusText:o.statusText}),Error(`Stream request failed: ${o.status} ${o.statusText}`);if(!o.body)throw Error(`No response body for stream`);return o.body}addInfoRequestLog(t,n,r,i){let a={method:r.method||`GET`,url:n,headers:(0,e.sanitizeHeaders)(i)};r.body&&(a.body=r.body),console.info(t,a)}addErrorRequestLog(e,t,n,r,i){console.error(`API Request Failed`,{method:t.method,url:e,status:n.status,statusText:n.statusText,duration:`${r}ms`,response:i})}addErrorRequestParsing(e,t,n,r,i){console.error(`API Response Parse Error`,{method:t.method,url:e,status:n.status,statusText:n.statusText,duration:`${r}ms`,responseText:i.substring(0,200),error:`Response is not valid JSON`})}};exports.AttachmentType=p,exports.COMPLETION_FINISH_REASON=i,exports.CUSTOM_VIEW_STATE_KEY=l,exports.ChatStreamSSEClient=j,exports.ConversationApi=L,exports.DIAL_API_ROUTES=r,exports.DIAL_ERROR_CODES=o,exports.DIAL_ERROR_TYPES=s,exports.DialApiClient=R,exports.ERROR_CONTEXT_KIND=u,exports.EXCEEDED_LIMIT=a,exports.EXCEEDED_LIMIT_ORDER=c,exports.InvitationType=m,exports.ResourceTypes=d,exports.ShareTarget=f,exports.chatStreamSSEClient=M,exports.decodeApiUrl=D,exports.encodeApiUrl=E,exports.formatDateTime=A,exports.generateConversationId=C,exports.getErrorMessage=_,exports.getRateLimitRestoreDate=O,exports.getSharedConversationsRequest=w,exports.handleStreamMessage=g,exports.isRateLimitStillActive=k,exports.mergeMessages=y,exports.parseConversationName=S,exports.sendRequest=T,exports.streamChatResponse=N;