@botpress/sdk 0.11.6 → 0.11.7

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.
@@ -1,12 +1,12 @@
1
1
 
2
- > @botpress/sdk@0.11.6 build /home/runner/work/botpress/botpress/packages/sdk
2
+ > @botpress/sdk@0.11.7 build /home/runner/work/botpress/botpress/packages/sdk
3
3
  > pnpm build:type && pnpm build:node
4
4
 
5
5
 
6
- > @botpress/sdk@0.11.6 build:type /home/runner/work/botpress/botpress/packages/sdk
6
+ > @botpress/sdk@0.11.7 build:type /home/runner/work/botpress/botpress/packages/sdk
7
7
  > tsc --emitDeclarationOnly --declaration
8
8
 
9
9
 
10
- > @botpress/sdk@0.11.6 build:node /home/runner/work/botpress/botpress/packages/sdk
10
+ > @botpress/sdk@0.11.7 build:node /home/runner/work/botpress/botpress/packages/sdk
11
11
  > ts-node -T build.ts
12
12
 
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Oe=Object.create;var O=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty;var S=(n,e)=>{for(var s in e)O(n,s,{get:e[s],enumerable:!0})},j=(n,e,s,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!Ne.call(n,i)&&i!==s&&O(n,i,{get:()=>e[i],enumerable:!(o=Fe(e,i))||o.enumerable});return n},h=(n,e,s)=>(j(n,e,"default"),s&&j(s,e,"default")),ce=(n,e,s)=>(s=n!=null?Oe(Ge(n)):{},j(e||!n||!n.__esModule?O(s,"default",{value:n,enumerable:!0}):s,n)),Ke=n=>j(O({},"__esModule",{value:!0}),n);var b={};S(b,{Bot:()=>L,BotSpecificClient:()=>A,Integration:()=>z,IntegrationDefinition:()=>C,IntegrationSpecificClient:()=>M,InterfaceDeclaration:()=>d,RuntimeError:()=>Z.RuntimeError,botIdHeader:()=>w,botUserIdHeader:()=>W,configurationHeader:()=>R,configurationTypeHeader:()=>Y,integrationIdHeader:()=>Q,interfaces:()=>ae,isApiError:()=>Z.isApiError,messages:()=>H,operationHeader:()=>_,parseBody:()=>f,serve:()=>k,typeHeader:()=>ee,webhookIdHeader:()=>X});module.exports=Ke(b);var H={};S(H,{defaults:()=>F});var r={};S(r,{default:()=>t});var le=require("@bpinternal/zui");h(r,require("@bpinternal/zui"));var t=le.z;var u=r.z.string().min(1),ge=r.z.object({text:u}),de=r.z.object({markdown:u}),me=r.z.object({imageUrl:u}),ue=r.z.object({audioUrl:u}),he=r.z.object({videoUrl:u}),Te=r.z.object({fileUrl:u,title:u.optional()}),fe=r.z.object({latitude:r.z.number(),longitude:r.z.number(),address:r.z.string().optional(),title:r.z.string().optional()}),be=r.z.object({title:u,subtitle:u.optional(),imageUrl:u.optional(),actions:r.z.array(r.z.object({action:r.z.enum(["postback","url","say"]),label:u,value:u}))}),pe=r.z.object({text:u,options:r.z.array(r.z.object({label:u,value:u}))}),ze=r.z.object({items:r.z.array(be)}),Le=r.z.discriminatedUnion("type",[r.z.object({type:r.z.literal("text"),payload:ge}),r.z.object({type:r.z.literal("markdown"),payload:de}),r.z.object({type:r.z.literal("image"),payload:me}),r.z.object({type:r.z.literal("audio"),payload:ue}),r.z.object({type:r.z.literal("video"),payload:he}),r.z.object({type:r.z.literal("file"),payload:Te}),r.z.object({type:r.z.literal("location"),payload:fe})]),Ze=r.z.object({items:r.z.array(Le)}),F={text:{schema:ge},markdown:{schema:de},image:{schema:me},audio:{schema:ue},video:{schema:he},file:{schema:Te},location:{schema:fe},carousel:{schema:ze},card:{schema:be},dropdown:{schema:pe},choice:{schema:pe},bloc:{schema:Ze}};var ae={};S(ae,{creatable:()=>vt,deletable:()=>St,hitl:()=>pt,listable:()=>It,llm:()=>ht,readable:()=>xt,schemas:()=>J,speechToText:()=>bt,textToImage:()=>Mt,typingIndicator:()=>Pt,updatable:()=>Bt});var J={};S(J,{speechToText:()=>$});var $={};S($,{OpenAITranscribeAudioOutputSchema:()=>V});var V=t.object({language:t.string().describe("Detected language of the audio"),duration:t.number().describe("Duration of the audio file, in seconds"),segments:t.array(t.object({text:t.string().describe("Text content of the segment."),id:t.number().describe("Unique identifier of the segment"),seek:t.number().describe("Seek offset of the segment"),start:t.number().describe("Start time of the segment in seconds."),end:t.number().describe("End time of the segment in seconds."),tokens:t.array(t.number()).describe("Array of token IDs for the text content."),temperature:t.number().describe("Temperature parameter used for generating the segment."),avg_logprob:t.number().describe("Average logprob of the segment. If the value is lower than -1, consider the logprobs failed."),compression_ratio:t.number().describe("Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed."),no_speech_prob:t.number().describe("Probability of no speech in the segment. If the value is higher than 1.0 and the avg_logprob is below -1, consider this segment silent.")}))});var ye=require("@bpinternal/zui");var w="x-bot-id",W="x-bot-user-id",Q="x-integration-id",X="x-webhook-id",Y="x-bp-configuration-type",R="x-bp-configuration",_="x-bp-operation",ee="x-bp-type";var qe=ye.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),Ie=n=>{let e=n[w],s=n[W],o=n[Q],i=n[X],a=n[Y],c=n[R],l=qe.parse(n[_]);if(!e)throw new Error("Missing bot headers");if(!s)throw new Error("Missing bot user headers");if(!o)throw new Error("Missing integration headers");if(!i)throw new Error("Missing webhook headers");if(!c)throw new Error("Missing configuration headers");if(!l)throw new Error("Missing operation headers");return{botId:e,botUserId:s,integrationId:o,webhookId:i,operation:l,configurationType:a??null,configuration:c?JSON.parse(Buffer.from(c,"base64").toString("utf-8")):{}}};var Ve=n=>Array.from(new Set(n)),I=n=>Object.entries(n);var x=(n,e)=>Object.fromEntries(I(n).map(([s,o])=>[s,e(o,s)])),U=(n,e,s)=>{let o=Ve([...Object.keys(n),...Object.keys(e)]),i={};for(let a of o){let c=n[a],l=e[a];c&&l?i[a]=s(c,l):c?i[a]=c:l&&(i[a]=l)}return i};var ne=Symbol("schemaName"),ve=n=>n?x(n,(s,o)=>({...s,[ne]:o})):{},xe=n=>n[ne]!==void 0,Be=n=>n[ne];var C=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.configurations=e.configurations,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;configurations;events;actions;channels;states;user;secrets;identifier;entities;interfaces={};clone(e){let s=new C({...this,...e});for(let[o,i]of Object.entries(this.interfaces))s.interfaces[o]=i;return s}extend(e,s){let o=s(ve(this.entities)),i=I(o).find(([m,v])=>!xe(v));if(i)throw new Error(`Cannot extend interface "${e.name}" with entity "${i[0]}"; the provided schema is not part of the integration's entities.`);let a=x(o,m=>({name:Be(m),schema:m.schema})),{resolved:c,implementStatement:l}=e.resolve({entities:a}),p=this;p.actions=U(p.actions??{},c.actions,this._mergeActions),p.channels=U(p.channels??{},c.channels,this._mergeChannels),p.events=U(p.events??{},c.events,this._mergeEvents);let g=Object.values(a).map(m=>m.name),T=g.length===0?e.name:`${e.name}<${g.join(",")}>`;return this.interfaces[T]=l,this}_mergeActions=(e,s)=>({...e,...s,input:{schema:e.input.schema.merge(s.input.schema)},output:{schema:e.output.schema.merge(s.output.schema)}});_mergeEvents=(e,s)=>({...e,...s,schema:e.schema.merge(s.schema)});_mergeChannels=(e,s)=>{let o=U(e.messages,s.messages,this._mergeMessage);return{...e,...s,messages:o}};_mergeMessage=(e,s)=>({schema:e.schema.merge(s.schema)})};var d=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.entities=e.entities??{},this.events=e.events??{},this.actions=e.actions??{},this.channels=e.channels??{},this.templateName=e.templateName}name;version;entities;events;actions;channels;templateName;resolve(e){let{entities:s}=e,o={name:this.name,version:this.version,entities:x(s,p=>({name:p.name})),actions:{},events:{}},i={},a={},c={};for(let[p,g]of I(this.actions)){let T=this._dereference(g.input.schema,s),m=this._dereference(g.output.schema,s),v=this._rename(s,p);i[v]={...g,input:{schema:T},output:{schema:m}},o.actions[p]={name:v}}for(let[p,g]of I(this.events)){let T=this._dereference(g.schema,s),m=this._rename(s,p);a[m]={...g,schema:T},o.events[p]={name:m}}for(let[p,g]of I(this.channels)){let T={};for(let[m,v]of I(g.messages)){let q=this._dereference(v.schema,s);T[m]={...v,schema:q}}c[p]={...g,messages:T}}return{resolved:{actions:i,events:a,channels:c},implementStatement:o}}_dereference(e,s){let o={},i={};for(let[a,c]of I(s))o[a]=c.schema,i[a]=t.ref(a);return e(i).dereference(o)}_rename(e,s){if(!this.templateName)return s;let o=x(e,i=>i.name);return this.templateName(s,o)}};var Se=require("node:http");var E=console;function f(n){if(!n.body)throw new Error("Missing body");return JSON.parse(n.body)}async function k(n,e=8072,s=Qe){let o=(0,Se.createServer)(async(i,a)=>{try{let c=await $e(i);if(c.path==="/health"){a.writeHead(200).end("ok");return}let l=await n(c);a.writeHead(l?.status??200,l?.headers??{}).end(l?.body??"{}")}catch(c){E.error("Error while handling request",{error:c?.message??"Internal error occured"}),a.writeHead(500).end(JSON.stringify({error:c?.message??"Internal error occured"}))}});return o.listen(e,()=>s(e)),o}async function $e(n){let e=await We(n),s={};for(let i=0;i<n.rawHeaders.length;i+=2){let a=n.rawHeaders[i].toLowerCase(),c=n.rawHeaders[i+1];s[a]=c}let o=new URL(n.url??"",n.headers.host?`http://${n.headers.host}`:"http://botpress.cloud");return{body:e,path:o.pathname,query:Je(o.search,"?"),headers:s,method:n.method?.toUpperCase()??"GET"}}function Je(n,e){return n.indexOf(e)===0?n.slice(e.length):n}async function We(n){return new Promise((e,s)=>{if(n.method!=="POST"&&n.method!=="PUT"&&n.method!=="PATCH")return e(void 0);let o="";n.on("data",i=>o+=i.toString()),n.on("error",i=>s(i)),n.on("end",()=>e(o))})}function Qe(n){E.info(`Listening on port ${n}`)}var B=require("@botpress/client");var Ce=require("@botpress/client"),G={retries:3,retryCondition:n=>Ce.axiosRetry.isNetworkOrIdempotentRequestError(n)||[429,502].includes(n.response?.status??0),retryDelay:n=>n*1e3};var M=class{constructor(e){this._client=e}createConversation=e=>this._client.createConversation(e);getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);createEvent=e=>this._client.createEvent(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);createUser=e=>this._client.createUser(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e);setState=e=>this._client.setState(e);getOrSetState=e=>this._client.getOrSetState(e);patchState=e=>this._client.patchState(e);configureIntegration=e=>this._client.configureIntegration(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e)};var se=ce(require("util")),N=n=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:se.default.format(...n),visible_to_bot_owner:!0});{let[e,...s]=n;return se.default.format(`[For Bot Owner] ${e}`,...s)}},K={forBot:()=>({info:(...n)=>{console.info(N(n))},warn:(...n)=>{console.warn(N(n))},error:(...n)=>{console.error(N(n))},debug:(...n)=>{console.debug(N(n))}})};var Ee=n=>async e=>{let s=Ie(e.headers),o=new B.Client({botId:s.botId,integrationId:s.integrationId,retry:G}),i=new M(o),a={ctx:s,req:e,client:i,logger:K,instance:n};try{let c;switch(s.operation){case"webhook_received":c=await Ye(a);break;case"register":c=await et(a);break;case"unregister":c=await tt(a);break;case"message_created":c=await ot(a);break;case"action_triggered":c=await it(a);break;case"ping":c=await Xe(a);break;case"create_user":c=await nt(a);break;case"create_conversation":c=await st(a);break;default:throw new Error(`Unknown operation ${s.operation}`)}return c?{...c,status:c.status??200}:{status:200}}catch(c){if((0,B.isApiError)(c)){let p=new B.RuntimeError(c.message,c);return K.forBot().error(p.message),{status:p.code,body:JSON.stringify(p.toJSON())}}console.error(c);let l=new B.RuntimeError("An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.");return K.forBot().error(l.message),{status:l.code,body:JSON.stringify(l.toJSON())}}},Xe=async n=>{},Ye=async({client:n,ctx:e,req:s,logger:o,instance:i})=>{let{req:a}=f(s);return i.webhook({client:n,ctx:e,req:a,logger:o})},et=async({client:n,ctx:e,req:s,logger:o,instance:i})=>{if(!i.register)return;let{webhookUrl:a}=f(s);await i.register({client:n,ctx:e,webhookUrl:a,logger:o})},tt=async({client:n,ctx:e,req:s,logger:o,instance:i})=>{if(!i.unregister)return;let{webhookUrl:a}=f(s);await i.unregister({ctx:e,webhookUrl:a,client:n,logger:o})},nt=async({client:n,ctx:e,req:s,logger:o,instance:i})=>{if(!i.createUser)return;let{tags:a}=f(s);return await i.createUser({ctx:e,client:n,tags:a,logger:o})},st=async({client:n,ctx:e,req:s,logger:o,instance:i})=>{if(!i.createConversation)return;let{channel:a,tags:c}=f(s);return await i.createConversation({ctx:e,client:n,channel:a,tags:c,logger:o})},ot=async({ctx:n,req:e,client:s,logger:o,instance:i})=>{let{conversation:a,user:c,type:l,payload:p,message:g}=f(e),T=i.channels[a.channel];if(!T)throw new Error(`Channel ${a.channel} not found`);let m=T.messages[l];if(!m)throw new Error(`Message of type ${l} not found in channel ${a.channel}`);await m({ctx:n,conversation:a,message:g,user:c,type:l,client:s,payload:p,ack:async({tags:q})=>{await s.updateMessage({id:g.id,tags:q})},logger:o})},it=async({req:n,ctx:e,client:s,logger:o,instance:i})=>{let{input:a,type:c}=f(n);if(!c)throw new Error("Missing action type");let l=i.actions[c];if(!l)throw new Error(`Action ${c} not found`);let p=await l({ctx:e,input:a,client:s,type:c,logger:o});return{body:JSON.stringify({output:p})}};var z=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=Ee(this);start=e=>k(this.handler,e)};var rt=n=>({...n,schema:()=>n.schema.extend({userId:t.string().optional().describe("Allows sending a message pretending to be a certain user")})}),at=t.union([t.object({type:t.literal("user"),userId:t.string()}),t.object({type:t.literal("bot")})]),ct=Object.entries(F).map(([n,e])=>t.object({source:at,type:t.literal(n),payload:e.schema})),lt=t.union(ct),pt=new d({name:"hitl",version:"0.4.0",entities:{},events:{hitlAssigned:{schema:()=>t.object({conversationId:t.string(),userId:t.string()})},hitlStopped:{schema:()=>t.object({conversationId:t.string()})}},actions:{createUser:{input:{schema:()=>t.object({name:t.string().optional(),pictureUrl:t.string().optional(),email:t.string().optional()})},output:{schema:()=>t.object({userId:t.string()})}},startHitl:{input:{schema:()=>t.object({userId:t.string(),title:t.string(),description:t.string().optional(),messageHistory:t.array(lt).optional().describe("Message history to display in the HITL session")})},output:{schema:()=>t.object({conversationId:t.string()})}},stopHitl:{input:{schema:()=>t.object({conversationId:t.string(),reason:t.enum(["timeout","cancel"]).optional()})},output:{schema:()=>t.object({})}}},channels:{hitl:{messages:{text:rt(F.text)}}}});var gt=t.object({id:t.string(),type:t.enum(["function"]),function:t.object({name:t.string(),arguments:t.record(t.any()).nullable().describe("Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.")})}),dt=t.object({type:t.enum(["auto","specific","any","none",""]).optional(),functionName:t.string().optional().describe('Required if `type` is "specific"')}),Me=t.object({role:t.enum(["user","assistant"]),type:t.enum(["text","tool_calls","tool_result","multipart"]).default("text"),toolCalls:t.array(gt).optional().describe('Required if `type` is "tool_calls"'),toolResultCallId:t.string().optional().describe('Required if `type` is "tool_result"'),content:t.string().or(t.array(t.object({type:t.enum(["text","image"]),mimeType:t.string().optional().describe("Indicates the MIME type of the content. If not provided it will be detected from the content-type header of the provided URL."),text:t.string().optional().describe('Required if part type is "text" '),url:t.string().optional().describe('Required if part type is "image"')}))).optional().nullable().describe('Required unless `type` is "tool_call". If `type` is "multipart", this field must be an array of content objects. If `type` is "tool_result" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is "tool_call" then the `toolCalls` field should be used instead.')}),oe=t.object({id:t.string()}),mt=oe.extend({name:t.string(),description:t.string(),tags:t.array(t.enum(["recommended","deprecated","general-purpose","low-cost","vision","coding","agents","function-calling","roleplay","storytelling"])),input:t.object({maxTokens:t.number().int(),costPer1MTokens:t.number().describe("Cost per 1 million tokens, in U.S. dollars")}),output:t.object({maxTokens:t.number().int(),costPer1MTokens:t.number().describe("Cost per 1 million tokens, in U.S. dollars")})}),Pe=n=>t.object({model:n.describe("Model to use for content generation").optional(),systemPrompt:t.string().optional().describe("Optional system prompt to guide the model"),messages:t.array(Me).describe("Array of messages for the model to process"),responseFormat:t.enum(["text","json_object"]).optional().describe('Response format expected from the model. If "json_object" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'),maxTokens:t.number().optional().describe("Maximum number of tokens allowed in the generated response"),temperature:t.number().min(0).max(2).displayAs({id:"slider",params:{stepSize:.01,horizontal:!0}}).default(1).describe("Sampling temperature for the model. Higher values result in more random outputs."),topP:t.number().min(0).max(1).default(1).displayAs({id:"slider",params:{stepSize:.01,horizontal:!0}}).describe("Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold."),stopSequences:t.array(t.string()).max(4).optional().describe("Sequences where the model should stop generating further tokens."),tools:t.array(t.object({type:t.literal("function"),function:t.object({name:t.string().describe("Function name"),description:t.string().optional(),argumentsSchema:t.object({}).passthrough().optional().describe("JSON schema of the function arguments")})})).optional(),toolChoice:dt.optional(),userId:t.string().optional(),debug:t.boolean().optional().describe("Set to `true` to output debug information to the bot logs")}),Kn=Pe(oe),ut=t.object({id:t.string().describe("Response ID from LLM provider"),provider:t.string().describe("LLM provider name"),model:t.string().describe("Model name"),choices:t.array(Me.omit({role:!0}).extend({role:t.literal("assistant"),index:t.number().int(),stopReason:t.enum(["stop","max_tokens","tool_calls","content_filter","other"])})),usage:t.object({inputTokens:t.number().int().describe("Number of input tokens used by the model"),inputCost:t.number().describe("Cost of the input tokens received by the model, in U.S. dollars"),outputTokens:t.number().int().describe("Number of output tokens used by the model"),outputCost:t.number().describe("Cost of the output tokens generated by the model, in U.S. dollars")}),botpress:t.object({cost:t.number().describe("Total cost of the content generation, in U.S. dollars")})}),ht=new d({name:"llm",version:"5.0.0",entities:{modelRef:{schema:oe}},events:{},actions:{generateContent:{billable:!0,cacheable:!0,input:{schema:({modelRef:n})=>Pe(n)},output:{schema:()=>ut}},listLanguageModels:{input:{schema:()=>t.object({})},output:{schema:({modelRef:n})=>t.object({models:t.array(t.intersection(mt,n))})}}}});var ie=t.object({id:t.string()}),Tt=ie.extend({name:t.string(),costPerMinute:t.number().describe("Cost per minute of speech transcription, in U.S. dollars")}),Ae=n=>t.object({model:n.optional().describe("Model to use for speech-to-text transcription (optional)"),fileUrl:t.string().url().describe("URL of the audio file to transcribe. The URL should return a content-type header in order to detect the audio format. Supported audio formats supported are: mp3, mp4, mpeg, mpga, m4a, wav, webm"),language:t.string().optional().describe("The language of the input audio (optional). Supplying the input language in ISO-639-1 format will improve accuracy and latency."),prompt:t.string().optional().describe("An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language."),temperature:t.number().default(0).optional().describe("The sampling temperature (optional), between 0 and 1. Defaults to 0 (automatic). Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.")}),Vn=Ae(ie),ft=V.extend({model:t.string().describe("Model name used"),cost:t.number().describe("Total cost of the transcription, in U.S. dollars (DEPRECATED)"),botpress:t.object({cost:t.number().describe("Total cost of the transcription, in U.S. dollars")})}),bt=new d({name:"speechToText",version:"2.0.0",entities:{speechToTextModelRef:{schema:ie}},actions:{transcribeAudio:{billable:!0,cacheable:!0,input:{schema:({speechToTextModelRef:n})=>Ae(n)},output:{schema:()=>ft}},listSpeechToTextModels:{input:{schema:()=>t.object({})},output:{schema:({speechToTextModelRef:n})=>t.object({models:t.array(t.intersection(Tt,n))})}}}});var y=t.object({id:t.string()}),P=n=>t.intersection(n,y),yt=n=>n[0].toUpperCase()+n.slice(1),D=(...n)=>{let[e,...s]=n.filter(o=>o.length>0).map(o=>o.toLowerCase());return e?[e,...s.map(yt)].join(""):""},we=t.string().optional(),It=new d({name:"listable",version:"0.0.1",entities:{item:{schema:y}},events:{},actions:{list:{input:{schema:()=>t.object({nextToken:we})},output:{schema:n=>t.object({items:t.array(P(n.item)),meta:t.object({nextToken:we})})}}},templateName:(n,e)=>D(e.item,n)}),vt=new d({name:"creatable",version:"0.0.1",entities:{item:{schema:y}},events:{created:{schema:n=>t.object({item:P(n.item)})}},actions:{create:{input:{schema:n=>t.object({item:n.item})},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),xt=new d({name:"readable",version:"0.0.1",entities:{item:{schema:y}},events:{},actions:{read:{input:{schema:()=>y},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),Bt=new d({name:"updatable",version:"0.0.1",entities:{item:{schema:y}},events:{updated:{schema:n=>t.object({item:P(n.item)})}},actions:{update:{input:{schema:n=>y.extend({item:n.item})},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),St=new d({name:"deletable",version:"0.0.1",entities:{item:{schema:y}},events:{deleted:{schema:()=>y}},actions:{delete:{input:{schema:()=>y},output:{schema:()=>t.object({})}}},templateName:(n,e)=>D(e.item,n)});var re=t.object({id:t.string()}),Ct=re.extend({name:t.string(),costPerImage:t.number().describe("Cost per image generation, in U.S. dollars"),sizes:t.array(t.string()).describe("Available image sizes"),defaultSize:t.string().describe("Default image size generated by model")}),Re=t.object({}).describe("Model-specific parameters for image generation"),_e=(n,e)=>t.object({model:n.optional().describe("Model to use for image generation"),prompt:t.string(),size:t.string().optional(),expiration:t.number().int().min(30).max(90).optional().describe("Expiration of the generated image in days, after which the image will be automatically deleted to free up storage space in your account. The default is to keep the image indefinitely (no expiration). The minimum is 30 days and the maximum is 90 days."),params:e.optional()}),es=_e(re,Re),Et=t.object({model:t.string().describe("Model name used"),imageUrl:t.string().describe("Temporary URL of generated image"),cost:t.number().describe("Cost of the image generation, in U.S. dollars (DEPRECATED)"),botpress:t.object({cost:t.number().describe("Cost of the image generation, in U.S. dollars")})}),Mt=new d({name:"textToImage",version:"2.1.0",entities:{imageModelRef:{schema:re},imageGenerationParams:{schema:Re}},actions:{generateImage:{billable:!0,cacheable:!0,input:{schema:({imageModelRef:n,imageGenerationParams:e})=>_e(n,e)},output:{schema:()=>Et}},listImageModels:{input:{schema:()=>t.object({})},output:{schema:({imageModelRef:n})=>t.object({models:t.array(t.intersection(Ct,n))})}}}});var Pt=new d({name:"typingIndicator",version:"0.0.1",entities:{},events:{},actions:{startTypingIndicator:{input:{schema:()=>t.object({conversationId:t.string(),messageId:t.string().describe("The message ID to which the typing indicator should be attached"),timeout:t.number().optional().describe("The timeout in milliseconds after which the typing indicator should stop")})},output:{schema:()=>t.object({})}},stopTypingIndicator:{input:{schema:()=>t.object({conversationId:t.string(),messageId:t.string().describe("The message ID from which the typing indicator should be removed")})},output:{schema:()=>t.object({})}}}});h(b,r,module.exports);var Z=require("@botpress/client");var De=ce(require("@botpress/client"));var A=class{constructor(e){this._client=e}getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e).then(s=>({state:{...s.state,payload:s.state.payload}}));setState=e=>this._client.setState(e).then(s=>({state:{...s.state,payload:s.state.payload}}));getOrSetState=e=>this._client.getOrSetState(e).then(s=>({state:{...s.state,payload:s.state.payload}}));patchState=e=>this._client.patchState(e).then(s=>({state:{...s.state,payload:s.state.payload}}));callAction=e=>this._client.callAction(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e);searchFiles=e=>this._client.searchFiles(e);createConversation=e=>this._client.createConversation(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);createUser=e=>this._client.createUser(e);getOrCreateUser=e=>this._client.getOrCreateUser(e)};var Ue=require("@bpinternal/zui");var At=Ue.z.enum(["event_received","register","unregister","ping","action_triggered"]),ke=n=>{let e=n[w],s=n[R],o=n[ee],i=At.parse(n[_]);if(!e)throw new Error("Missing bot headers");if(!o)throw new Error("Missing type headers");if(!s)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,operation:i,type:o,configuration:s?JSON.parse(Buffer.from(s,"base64").toString("utf-8")):{}}};var je=n=>async e=>{let s=ke(e.headers);s.operation!=="ping"&&E.info(`Received ${s.operation} operation for bot ${s.botId} of type ${s.type}`);let o=new De.Client({botId:s.botId,retry:G}),i=new A(o),a={req:e,ctx:s,client:i,instance:n};switch(s.operation){case"action_triggered":throw new Error(`Operation ${s.operation} not supported yet`);case"event_received":await Ut(a);break;case"register":await Rt(a);break;case"unregister":await _t(a);break;case"ping":await wt(a);break;default:throw new Error(`Unknown operation ${s.operation}`)}return{status:200}},wt=async n=>{},Rt=async n=>{},_t=async n=>{},Ut=async({ctx:n,req:e,client:s,instance:o})=>{E.debug(`Received event ${n.type}`);let i=f(e),a=i.event;switch(n.type){case"message_created":let c={user:a.payload.user,conversation:a.payload.conversation,message:a.payload.message,states:a.payload.states,event:a};await Promise.all(o.messageHandlers.map(g=>g({client:s,ctx:n,...c})));break;case"state_expired":let l={state:a.payload.state};await Promise.all(o.stateExpiredHandlers.map(g=>g({client:s,ctx:n,...l})));break;default:let p={event:i.event};await Promise.all(o.eventHandlers.map(g=>g({client:s,ctx:n,...p})))}};var L=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=je(this._state);start=e=>k(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,configurationTypeHeader,integrationIdHeader,interfaces,isApiError,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
1
+ "use strict";var Oe=Object.create;var O=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty;var S=(n,e)=>{for(var o in e)O(n,o,{get:e[o],enumerable:!0})},j=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!Ne.call(n,i)&&i!==o&&O(n,i,{get:()=>e[i],enumerable:!(s=Fe(e,i))||s.enumerable});return n},h=(n,e,o)=>(j(n,e,"default"),o&&j(o,e,"default")),ce=(n,e,o)=>(o=n!=null?Oe(Ge(n)):{},j(e||!n||!n.__esModule?O(o,"default",{value:n,enumerable:!0}):o,n)),Ke=n=>j(O({},"__esModule",{value:!0}),n);var b={};S(b,{Bot:()=>L,BotSpecificClient:()=>A,Integration:()=>z,IntegrationDefinition:()=>C,IntegrationSpecificClient:()=>M,InterfaceDeclaration:()=>d,RuntimeError:()=>Z.RuntimeError,botIdHeader:()=>w,botUserIdHeader:()=>W,configurationHeader:()=>R,configurationTypeHeader:()=>Y,integrationIdHeader:()=>Q,interfaces:()=>ae,isApiError:()=>Z.isApiError,messages:()=>H,operationHeader:()=>_,parseBody:()=>f,serve:()=>U,typeHeader:()=>ee,webhookIdHeader:()=>X});module.exports=Ke(b);var H={};S(H,{defaults:()=>F});var r={};S(r,{default:()=>t});var le=require("@bpinternal/zui");h(r,require("@bpinternal/zui"));var t=le.z;var u=r.z.string().min(1),ge=r.z.object({text:u}),de=r.z.object({markdown:u}),me=r.z.object({imageUrl:u}),ue=r.z.object({audioUrl:u}),he=r.z.object({videoUrl:u}),Te=r.z.object({fileUrl:u,title:u.optional()}),fe=r.z.object({latitude:r.z.number(),longitude:r.z.number(),address:r.z.string().optional(),title:r.z.string().optional()}),be=r.z.object({title:u,subtitle:u.optional(),imageUrl:u.optional(),actions:r.z.array(r.z.object({action:r.z.enum(["postback","url","say"]),label:u,value:u}))}),pe=r.z.object({text:u,options:r.z.array(r.z.object({label:u,value:u}))}),ze=r.z.object({items:r.z.array(be)}),Le=r.z.discriminatedUnion("type",[r.z.object({type:r.z.literal("text"),payload:ge}),r.z.object({type:r.z.literal("markdown"),payload:de}),r.z.object({type:r.z.literal("image"),payload:me}),r.z.object({type:r.z.literal("audio"),payload:ue}),r.z.object({type:r.z.literal("video"),payload:he}),r.z.object({type:r.z.literal("file"),payload:Te}),r.z.object({type:r.z.literal("location"),payload:fe})]),Ze=r.z.object({items:r.z.array(Le)}),F={text:{schema:ge},markdown:{schema:de},image:{schema:me},audio:{schema:ue},video:{schema:he},file:{schema:Te},location:{schema:fe},carousel:{schema:ze},card:{schema:be},dropdown:{schema:pe},choice:{schema:pe},bloc:{schema:Ze}};var ae={};S(ae,{creatable:()=>vt,deletable:()=>St,hitl:()=>pt,listable:()=>It,llm:()=>ht,readable:()=>xt,schemas:()=>J,speechToText:()=>bt,textToImage:()=>Mt,typingIndicator:()=>Pt,updatable:()=>Bt});var J={};S(J,{speechToText:()=>$});var $={};S($,{OpenAITranscribeAudioOutputSchema:()=>V});var V=t.object({language:t.string().describe("Detected language of the audio"),duration:t.number().describe("Duration of the audio file, in seconds"),segments:t.array(t.object({text:t.string().describe("Text content of the segment."),id:t.number().describe("Unique identifier of the segment"),seek:t.number().describe("Seek offset of the segment"),start:t.number().describe("Start time of the segment in seconds."),end:t.number().describe("End time of the segment in seconds."),tokens:t.array(t.number()).describe("Array of token IDs for the text content."),temperature:t.number().describe("Temperature parameter used for generating the segment."),avg_logprob:t.number().describe("Average logprob of the segment. If the value is lower than -1, consider the logprobs failed."),compression_ratio:t.number().describe("Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed."),no_speech_prob:t.number().describe("Probability of no speech in the segment. If the value is higher than 1.0 and the avg_logprob is below -1, consider this segment silent.")}))});var ye=require("@bpinternal/zui");var w="x-bot-id",W="x-bot-user-id",Q="x-integration-id",X="x-webhook-id",Y="x-bp-configuration-type",R="x-bp-configuration",_="x-bp-operation",ee="x-bp-type";var qe=ye.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),Ie=n=>{let e=n[w],o=n[W],s=n[Q],i=n[X],a=n[Y],c=n[R],l=qe.parse(n[_]);if(!e)throw new Error("Missing bot headers");if(!o)throw new Error("Missing bot user headers");if(!s)throw new Error("Missing integration headers");if(!i)throw new Error("Missing webhook headers");if(!c)throw new Error("Missing configuration headers");if(!l)throw new Error("Missing operation headers");return{botId:e,botUserId:o,integrationId:s,webhookId:i,operation:l,configurationType:a??null,configuration:c?JSON.parse(Buffer.from(c,"base64").toString("utf-8")):{}}};var Ve=n=>Array.from(new Set(n)),I=n=>Object.entries(n);var x=(n,e)=>Object.fromEntries(I(n).map(([o,s])=>[o,e(s,o)])),k=(n,e,o)=>{let s=Ve([...Object.keys(n),...Object.keys(e)]),i={};for(let a of s){let c=n[a],l=e[a];c&&l?i[a]=o(c,l):c?i[a]=c:l&&(i[a]=l)}return i};var ne=Symbol("schemaName"),ve=n=>n?x(n,(o,s)=>({...o,[ne]:s})):{},xe=n=>n[ne]!==void 0,Be=n=>n[ne];var C=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.icon=e.icon,this.readme=e.readme,this.title=e.title,this.identifier=e.identifier,this.description=e.description,this.configuration=e.configuration,this.configurations=e.configurations,this.events=e.events,this.actions=e.actions,this.channels=e.channels,this.states=e.states,this.user=e.user,this.secrets=e.secrets,this.entities=e.entities}name;version;title;description;icon;readme;configuration;configurations;events;actions;channels;states;user;secrets;identifier;entities;interfaces={};clone(e){let o=new C({...this,...e});for(let[s,i]of Object.entries(this.interfaces))o.interfaces[s]=i;return o}extend(e,o){let s=o(ve(this.entities)),i=I(s).find(([m,v])=>!xe(v));if(i)throw new Error(`Cannot extend interface "${e.name}" with entity "${i[0]}"; the provided schema is not part of the integration's entities.`);let a=x(s,m=>({name:Be(m),schema:m.schema})),{resolved:c,implementStatement:l}=e.resolve({entities:a}),p=this;p.actions=k(p.actions??{},c.actions,this._mergeActions),p.channels=k(p.channels??{},c.channels,this._mergeChannels),p.events=k(p.events??{},c.events,this._mergeEvents);let g=Object.values(a).map(m=>m.name),T=g.length===0?e.name:`${e.name}<${g.join(",")}>`;return this.interfaces[T]=l,this}_mergeActions=(e,o)=>({...e,...o,input:{schema:e.input.schema.merge(o.input.schema)},output:{schema:e.output.schema.merge(o.output.schema)}});_mergeEvents=(e,o)=>({...e,...o,schema:e.schema.merge(o.schema)});_mergeChannels=(e,o)=>{let s=k(e.messages,o.messages,this._mergeMessage);return{...e,...o,messages:s}};_mergeMessage=(e,o)=>({schema:e.schema.merge(o.schema)})};var d=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.entities=e.entities??{},this.events=e.events??{},this.actions=e.actions??{},this.channels=e.channels??{},this.templateName=e.templateName}name;version;entities;events;actions;channels;templateName;resolve(e){let{entities:o}=e,s={name:this.name,version:this.version,entities:x(o,p=>({name:p.name})),actions:{},events:{}},i={},a={},c={};for(let[p,g]of I(this.actions)){let T=this._dereference(g.input.schema,o),m=this._dereference(g.output.schema,o),v=this._rename(o,p);i[v]={...g,input:{schema:T},output:{schema:m}},s.actions[p]={name:v}}for(let[p,g]of I(this.events)){let T=this._dereference(g.schema,o),m=this._rename(o,p);a[m]={...g,schema:T},s.events[p]={name:m}}for(let[p,g]of I(this.channels)){let T={};for(let[m,v]of I(g.messages)){let q=this._dereference(v.schema,o);T[m]={...v,schema:q}}c[p]={...g,messages:T}}return{resolved:{actions:i,events:a,channels:c},implementStatement:s}}_dereference(e,o){let s={},i={};for(let[a,c]of I(o))s[a]=c.schema,i[a]=t.ref(a);return e(i).dereference(s)}_rename(e,o){if(!this.templateName)return o;let s=x(e,i=>i.name);return this.templateName(o,s)}};var Se=require("node:http");var E=console;function f(n){if(!n.body)throw new Error("Missing body");return JSON.parse(n.body)}async function U(n,e=8072,o=Qe){let s=(0,Se.createServer)(async(i,a)=>{try{let c=await $e(i);if(c.path==="/health"){a.writeHead(200).end("ok");return}let l=await n(c);a.writeHead(l?.status??200,l?.headers??{}).end(l?.body??"{}")}catch(c){E.error("Error while handling request",{error:c?.message??"Internal error occured"}),a.writeHead(500).end(JSON.stringify({error:c?.message??"Internal error occured"}))}});return s.listen(e,()=>o(e)),s}async function $e(n){let e=await We(n),o={};for(let i=0;i<n.rawHeaders.length;i+=2){let a=n.rawHeaders[i].toLowerCase(),c=n.rawHeaders[i+1];o[a]=c}let s=new URL(n.url??"",n.headers.host?`http://${n.headers.host}`:"http://botpress.cloud");return{body:e,path:s.pathname,query:Je(s.search,"?"),headers:o,method:n.method?.toUpperCase()??"GET"}}function Je(n,e){return n.indexOf(e)===0?n.slice(e.length):n}async function We(n){return new Promise((e,o)=>{if(n.method!=="POST"&&n.method!=="PUT"&&n.method!=="PATCH")return e(void 0);let s="";n.on("data",i=>s+=i.toString()),n.on("error",i=>o(i)),n.on("end",()=>e(s))})}function Qe(n){E.info(`Listening on port ${n}`)}var B=require("@botpress/client");var Ce=require("@botpress/client"),G={retries:3,retryCondition:n=>Ce.axiosRetry.isNetworkOrIdempotentRequestError(n)||[429,502].includes(n.response?.status??0),retryDelay:n=>n*1e3};var M=class{constructor(e){this._client=e}createConversation=e=>this._client.createConversation(e);getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);createEvent=e=>this._client.createEvent(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);createUser=e=>this._client.createUser(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);getOrCreateUser=e=>this._client.getOrCreateUser(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e);setState=e=>this._client.setState(e);getOrSetState=e=>this._client.getOrSetState(e);patchState=e=>this._client.patchState(e);configureIntegration=e=>this._client.configureIntegration(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e)};var oe=ce(require("util")),N=n=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:oe.default.format(...n),visible_to_bot_owner:!0});{let[e,...o]=n;return oe.default.format(`[For Bot Owner] ${e}`,...o)}},K={forBot:()=>({info:(...n)=>{console.info(N(n))},warn:(...n)=>{console.warn(N(n))},error:(...n)=>{console.error(N(n))},debug:(...n)=>{console.debug(N(n))}})};var Ee=n=>async e=>{let o=Ie(e.headers),s=new B.Client({botId:o.botId,integrationId:o.integrationId,retry:G}),i=new M(s),a={ctx:o,req:e,client:i,logger:K,instance:n};try{let c;switch(o.operation){case"webhook_received":c=await Ye(a);break;case"register":c=await et(a);break;case"unregister":c=await tt(a);break;case"message_created":c=await st(a);break;case"action_triggered":c=await it(a);break;case"ping":c=await Xe(a);break;case"create_user":c=await nt(a);break;case"create_conversation":c=await ot(a);break;default:throw new Error(`Unknown operation ${o.operation}`)}return c?{...c,status:c.status??200}:{status:200}}catch(c){if((0,B.isApiError)(c)){let p=new B.RuntimeError(c.message,c);return K.forBot().error(p.message),{status:p.code,body:JSON.stringify(p.toJSON())}}console.error(c);let l=new B.RuntimeError("An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.");return K.forBot().error(l.message),{status:l.code,body:JSON.stringify(l.toJSON())}}},Xe=async n=>{},Ye=async({client:n,ctx:e,req:o,logger:s,instance:i})=>{let{req:a}=f(o);return i.webhook({client:n,ctx:e,req:a,logger:s})},et=async({client:n,ctx:e,req:o,logger:s,instance:i})=>{if(!i.register)return;let{webhookUrl:a}=f(o);await i.register({client:n,ctx:e,webhookUrl:a,logger:s})},tt=async({client:n,ctx:e,req:o,logger:s,instance:i})=>{if(!i.unregister)return;let{webhookUrl:a}=f(o);await i.unregister({ctx:e,webhookUrl:a,client:n,logger:s})},nt=async({client:n,ctx:e,req:o,logger:s,instance:i})=>{if(!i.createUser)return;let{tags:a}=f(o);return await i.createUser({ctx:e,client:n,tags:a,logger:s})},ot=async({client:n,ctx:e,req:o,logger:s,instance:i})=>{if(!i.createConversation)return;let{channel:a,tags:c}=f(o);return await i.createConversation({ctx:e,client:n,channel:a,tags:c,logger:s})},st=async({ctx:n,req:e,client:o,logger:s,instance:i})=>{let{conversation:a,user:c,type:l,payload:p,message:g}=f(e),T=i.channels[a.channel];if(!T)throw new Error(`Channel ${a.channel} not found`);let m=T.messages[l];if(!m)throw new Error(`Message of type ${l} not found in channel ${a.channel}`);await m({ctx:n,conversation:a,message:g,user:c,type:l,client:o,payload:p,ack:async({tags:q})=>{await o.updateMessage({id:g.id,tags:q})},logger:s})},it=async({req:n,ctx:e,client:o,logger:s,instance:i})=>{let{input:a,type:c}=f(n);if(!c)throw new Error("Missing action type");let l=i.actions[c];if(!l)throw new Error(`Action ${c} not found`);let p=await l({ctx:e,input:a,client:o,type:c,logger:s});return{body:JSON.stringify({output:p})}};var z=class{props;actions;channels;register;unregister;createUser;createConversation;webhook;constructor(e){this.props=e,this.actions=e.actions,this.channels=e.channels,this.register=e.register,this.unregister=e.unregister,this.createUser=e.createUser,this.createConversation=e.createConversation,this.webhook=e.handler}handler=Ee(this);start=e=>U(this.handler,e)};var rt=n=>({...n,schema:()=>n.schema.extend({userId:t.string().optional().describe("Allows sending a message pretending to be a certain user")})}),at=t.union([t.object({type:t.literal("user"),userId:t.string()}),t.object({type:t.literal("bot")})]),ct=Object.entries(F).map(([n,e])=>t.object({source:at,type:t.literal(n),payload:e.schema})),lt=t.union(ct),pt=new d({name:"hitl",version:"0.4.0",entities:{},events:{hitlAssigned:{schema:()=>t.object({conversationId:t.string(),userId:t.string()})},hitlStopped:{schema:()=>t.object({conversationId:t.string()})}},actions:{createUser:{input:{schema:()=>t.object({name:t.string().optional(),pictureUrl:t.string().optional(),email:t.string().optional()})},output:{schema:()=>t.object({userId:t.string()})}},startHitl:{input:{schema:()=>t.object({userId:t.string(),title:t.string(),description:t.string().optional(),messageHistory:t.array(lt).optional().describe("Message history to display in the HITL session")})},output:{schema:()=>t.object({conversationId:t.string()})}},stopHitl:{input:{schema:()=>t.object({conversationId:t.string(),reason:t.enum(["timeout","cancel"]).optional()})},output:{schema:()=>t.object({})}}},channels:{hitl:{messages:{text:rt(F.text)}}}});var gt=t.object({id:t.string(),type:t.enum(["function"]),function:t.object({name:t.string(),arguments:t.record(t.any()).nullable().describe("Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.")})}),dt=t.object({type:t.enum(["auto","specific","any","none",""]).optional(),functionName:t.string().optional().describe('Required if `type` is "specific"')}),Me=t.object({role:t.enum(["user","assistant"]),type:t.enum(["text","tool_calls","tool_result","multipart"]).default("text"),toolCalls:t.array(gt).optional().describe('Required if `type` is "tool_calls"'),toolResultCallId:t.string().optional().describe('Required if `type` is "tool_result"'),content:t.string().or(t.array(t.object({type:t.enum(["text","image"]),mimeType:t.string().optional().describe("Indicates the MIME type of the content. If not provided it will be detected from the content-type header of the provided URL."),text:t.string().optional().describe('Required if part type is "text" '),url:t.string().optional().describe('Required if part type is "image"')}))).optional().nullable().describe('Required unless `type` is "tool_call". If `type` is "multipart", this field must be an array of content objects. If `type` is "tool_result" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is "tool_call" then the `toolCalls` field should be used instead.')}),se=t.object({id:t.string()}),mt=se.extend({name:t.string(),description:t.string(),tags:t.array(t.enum(["recommended","deprecated","general-purpose","low-cost","vision","coding","agents","function-calling","roleplay","storytelling"])),input:t.object({maxTokens:t.number().int(),costPer1MTokens:t.number().describe("Cost per 1 million tokens, in U.S. dollars")}),output:t.object({maxTokens:t.number().int(),costPer1MTokens:t.number().describe("Cost per 1 million tokens, in U.S. dollars")})}),Pe=n=>t.object({model:n.describe("Model to use for content generation").optional(),systemPrompt:t.string().optional().describe("Optional system prompt to guide the model"),messages:t.array(Me).describe("Array of messages for the model to process"),responseFormat:t.enum(["text","json_object"]).optional().describe('Response format expected from the model. If "json_object" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'),maxTokens:t.number().optional().describe("Maximum number of tokens allowed in the generated response"),temperature:t.number().min(0).max(2).displayAs({id:"slider",params:{stepSize:.01,horizontal:!0}}).default(1).describe("Sampling temperature for the model. Higher values result in more random outputs."),topP:t.number().min(0).max(1).default(1).displayAs({id:"slider",params:{stepSize:.01,horizontal:!0}}).describe("Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold."),stopSequences:t.array(t.string()).max(4).optional().describe("Sequences where the model should stop generating further tokens."),tools:t.array(t.object({type:t.literal("function"),function:t.object({name:t.string().describe("Function name"),description:t.string().optional(),argumentsSchema:t.object({}).passthrough().optional().describe("JSON schema of the function arguments")})})).optional(),toolChoice:dt.optional(),userId:t.string().optional(),debug:t.boolean().optional().hidden().describe("Set to `true` to output debug information to the bot logs"),meta:t.object({promptCategory:t.string().optional().describe("Category of the prompt, e.g. cards/ai-generate, cards/ai-task, nodes/autonomous, etc."),integrationName:t.string().optional().describe("Name of the integration that originally received the message that initiated this action")}).optional().hidden()}),Kn=Pe(se),ut=t.object({id:t.string().describe("Response ID from LLM provider"),provider:t.string().describe("LLM provider name"),model:t.string().describe("Model name"),choices:t.array(Me.omit({role:!0}).extend({role:t.literal("assistant"),index:t.number().int(),stopReason:t.enum(["stop","max_tokens","tool_calls","content_filter","other"])})),usage:t.object({inputTokens:t.number().int().describe("Number of input tokens used by the model"),inputCost:t.number().describe("Cost of the input tokens received by the model, in U.S. dollars"),outputTokens:t.number().int().describe("Number of output tokens used by the model"),outputCost:t.number().describe("Cost of the output tokens generated by the model, in U.S. dollars")}),botpress:t.object({cost:t.number().describe("Total cost of the content generation, in U.S. dollars")})}),ht=new d({name:"llm",version:"5.1.0",entities:{modelRef:{schema:se}},events:{},actions:{generateContent:{billable:!0,cacheable:!0,input:{schema:({modelRef:n})=>Pe(n)},output:{schema:()=>ut}},listLanguageModels:{input:{schema:()=>t.object({})},output:{schema:({modelRef:n})=>t.object({models:t.array(t.intersection(mt,n))})}}}});var ie=t.object({id:t.string()}),Tt=ie.extend({name:t.string(),costPerMinute:t.number().describe("Cost per minute of speech transcription, in U.S. dollars")}),Ae=n=>t.object({model:n.optional().describe("Model to use for speech-to-text transcription (optional)"),fileUrl:t.string().url().describe("URL of the audio file to transcribe. The URL should return a content-type header in order to detect the audio format. Supported audio formats supported are: mp3, mp4, mpeg, mpga, m4a, wav, webm"),language:t.string().optional().describe("The language of the input audio (optional). Supplying the input language in ISO-639-1 format will improve accuracy and latency."),prompt:t.string().optional().describe("An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language."),temperature:t.number().default(0).optional().describe("The sampling temperature (optional), between 0 and 1. Defaults to 0 (automatic). Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.")}),Vn=Ae(ie),ft=V.extend({model:t.string().describe("Model name used"),cost:t.number().describe("Total cost of the transcription, in U.S. dollars (DEPRECATED)"),botpress:t.object({cost:t.number().describe("Total cost of the transcription, in U.S. dollars")})}),bt=new d({name:"speechToText",version:"2.0.0",entities:{speechToTextModelRef:{schema:ie}},actions:{transcribeAudio:{billable:!0,cacheable:!0,input:{schema:({speechToTextModelRef:n})=>Ae(n)},output:{schema:()=>ft}},listSpeechToTextModels:{input:{schema:()=>t.object({})},output:{schema:({speechToTextModelRef:n})=>t.object({models:t.array(t.intersection(Tt,n))})}}}});var y=t.object({id:t.string()}),P=n=>t.intersection(n,y),yt=n=>n[0].toUpperCase()+n.slice(1),D=(...n)=>{let[e,...o]=n.filter(s=>s.length>0).map(s=>s.toLowerCase());return e?[e,...o.map(yt)].join(""):""},we=t.string().optional(),It=new d({name:"listable",version:"0.0.1",entities:{item:{schema:y}},events:{},actions:{list:{input:{schema:()=>t.object({nextToken:we})},output:{schema:n=>t.object({items:t.array(P(n.item)),meta:t.object({nextToken:we})})}}},templateName:(n,e)=>D(e.item,n)}),vt=new d({name:"creatable",version:"0.0.1",entities:{item:{schema:y}},events:{created:{schema:n=>t.object({item:P(n.item)})}},actions:{create:{input:{schema:n=>t.object({item:n.item})},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),xt=new d({name:"readable",version:"0.0.1",entities:{item:{schema:y}},events:{},actions:{read:{input:{schema:()=>y},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),Bt=new d({name:"updatable",version:"0.0.1",entities:{item:{schema:y}},events:{updated:{schema:n=>t.object({item:P(n.item)})}},actions:{update:{input:{schema:n=>y.extend({item:n.item})},output:{schema:n=>t.object({item:P(n.item)})}}},templateName:(n,e)=>D(e.item,n)}),St=new d({name:"deletable",version:"0.0.1",entities:{item:{schema:y}},events:{deleted:{schema:()=>y}},actions:{delete:{input:{schema:()=>y},output:{schema:()=>t.object({})}}},templateName:(n,e)=>D(e.item,n)});var re=t.object({id:t.string()}),Ct=re.extend({name:t.string(),costPerImage:t.number().describe("Cost per image generation, in U.S. dollars"),sizes:t.array(t.string()).describe("Available image sizes"),defaultSize:t.string().describe("Default image size generated by model")}),Re=t.object({}).describe("Model-specific parameters for image generation"),_e=(n,e)=>t.object({model:n.optional().describe("Model to use for image generation"),prompt:t.string(),size:t.string().optional(),expiration:t.number().int().min(30).max(90).optional().describe("Expiration of the generated image in days, after which the image will be automatically deleted to free up storage space in your account. The default is to keep the image indefinitely (no expiration). The minimum is 30 days and the maximum is 90 days."),params:e.optional()}),eo=_e(re,Re),Et=t.object({model:t.string().describe("Model name used"),imageUrl:t.string().describe("Temporary URL of generated image"),cost:t.number().describe("Cost of the image generation, in U.S. dollars (DEPRECATED)"),botpress:t.object({cost:t.number().describe("Cost of the image generation, in U.S. dollars")})}),Mt=new d({name:"textToImage",version:"2.1.0",entities:{imageModelRef:{schema:re},imageGenerationParams:{schema:Re}},actions:{generateImage:{billable:!0,cacheable:!0,input:{schema:({imageModelRef:n,imageGenerationParams:e})=>_e(n,e)},output:{schema:()=>Et}},listImageModels:{input:{schema:()=>t.object({})},output:{schema:({imageModelRef:n})=>t.object({models:t.array(t.intersection(Ct,n))})}}}});var Pt=new d({name:"typingIndicator",version:"0.0.1",entities:{},events:{},actions:{startTypingIndicator:{input:{schema:()=>t.object({conversationId:t.string(),messageId:t.string().describe("The message ID to which the typing indicator should be attached"),timeout:t.number().optional().describe("The timeout in milliseconds after which the typing indicator should stop")})},output:{schema:()=>t.object({})}},stopTypingIndicator:{input:{schema:()=>t.object({conversationId:t.string(),messageId:t.string().describe("The message ID from which the typing indicator should be removed")})},output:{schema:()=>t.object({})}}}});h(b,r,module.exports);var Z=require("@botpress/client");var De=ce(require("@botpress/client"));var A=class{constructor(e){this._client=e}getConversation=e=>this._client.getConversation(e);listConversations=e=>this._client.listConversations(e);updateConversation=e=>this._client.updateConversation(e);deleteConversation=e=>this._client.deleteConversation(e);listParticipants=e=>this._client.listParticipants(e);addParticipant=e=>this._client.addParticipant(e);getParticipant=e=>this._client.getParticipant(e);removeParticipant=e=>this._client.removeParticipant(e);getEvent=e=>this._client.getEvent(e);listEvents=e=>this._client.listEvents(e);createMessage=e=>this._client.createMessage(e);getOrCreateMessage=e=>this._client.getOrCreateMessage(e);getMessage=e=>this._client.getMessage(e);updateMessage=e=>this._client.updateMessage(e);listMessages=e=>this._client.listMessages(e);deleteMessage=e=>this._client.deleteMessage(e);getUser=e=>this._client.getUser(e);listUsers=e=>this._client.listUsers(e);updateUser=e=>this._client.updateUser(e);deleteUser=e=>this._client.deleteUser(e);getState=e=>this._client.getState(e).then(o=>({state:{...o.state,payload:o.state.payload}}));setState=e=>this._client.setState(e).then(o=>({state:{...o.state,payload:o.state.payload}}));getOrSetState=e=>this._client.getOrSetState(e).then(o=>({state:{...o.state,payload:o.state.payload}}));patchState=e=>this._client.patchState(e).then(o=>({state:{...o.state,payload:o.state.payload}}));callAction=e=>this._client.callAction(e);uploadFile=e=>this._client.uploadFile(e);upsertFile=e=>this._client.upsertFile(e);deleteFile=e=>this._client.deleteFile(e);listFiles=e=>this._client.listFiles(e);getFile=e=>this._client.getFile(e);updateFileMetadata=e=>this._client.updateFileMetadata(e);searchFiles=e=>this._client.searchFiles(e);createConversation=e=>this._client.createConversation(e);getOrCreateConversation=e=>this._client.getOrCreateConversation(e);createUser=e=>this._client.createUser(e);getOrCreateUser=e=>this._client.getOrCreateUser(e)};var ke=require("@bpinternal/zui");var At=ke.z.enum(["event_received","register","unregister","ping","action_triggered"]),Ue=n=>{let e=n[w],o=n[R],s=n[ee],i=At.parse(n[_]);if(!e)throw new Error("Missing bot headers");if(!s)throw new Error("Missing type headers");if(!o)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,operation:i,type:s,configuration:o?JSON.parse(Buffer.from(o,"base64").toString("utf-8")):{}}};var je=n=>async e=>{let o=Ue(e.headers);o.operation!=="ping"&&E.info(`Received ${o.operation} operation for bot ${o.botId} of type ${o.type}`);let s=new De.Client({botId:o.botId,retry:G}),i=new A(s),a={req:e,ctx:o,client:i,instance:n};switch(o.operation){case"action_triggered":throw new Error(`Operation ${o.operation} not supported yet`);case"event_received":await kt(a);break;case"register":await Rt(a);break;case"unregister":await _t(a);break;case"ping":await wt(a);break;default:throw new Error(`Unknown operation ${o.operation}`)}return{status:200}},wt=async n=>{},Rt=async n=>{},_t=async n=>{},kt=async({ctx:n,req:e,client:o,instance:s})=>{E.debug(`Received event ${n.type}`);let i=f(e),a=i.event;switch(n.type){case"message_created":let c={user:a.payload.user,conversation:a.payload.conversation,message:a.payload.message,states:a.payload.states,event:a};await Promise.all(s.messageHandlers.map(g=>g({client:o,ctx:n,...c})));break;case"state_expired":let l={state:a.payload.state};await Promise.all(s.stateExpiredHandlers.map(g=>g({client:o,ctx:n,...l})));break;default:let p={event:i.event};await Promise.all(s.eventHandlers.map(g=>g({client:o,ctx:n,...p})))}};var L=class{_state={messageHandlers:[],eventHandlers:[],stateExpiredHandlers:[]};props;constructor(e){this.props=e}message=e=>{this._state.messageHandlers.push(e)};event=e=>{this._state.eventHandlers.push(e)};stateExpired=e=>{this._state.stateExpiredHandlers.push(e)};handler=je(this._state);start=e=>U(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,configurationTypeHeader,integrationIdHeader,interfaces,isApiError,messages,operationHeader,parseBody,serve,typeHeader,webhookIdHeader});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/message.ts", "../src/zui.ts", "../src/interfaces/index.ts", "../src/interfaces/schemas/index.ts", "../src/interfaces/schemas/speech-to-text.ts", "../src/integration/context.ts", "../src/const.ts", "../src/utils.ts", "../src/integration/definition/branded-schema.ts", "../src/integration/definition/integration-definition.ts", "../src/integration/definition/interface-declaration.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/server.ts", "../src/retry.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.ts", "../src/interfaces/hitl.ts", "../src/interfaces/llm.ts", "../src/interfaces/speech-to-text.ts", "../src/interfaces/sync.ts", "../src/interfaces/text-to-image.ts", "../src/interfaces/typing-indicator.ts", "../src/bot/server.ts", "../src/bot/client/index.ts", "../src/bot/context.ts", "../src/bot/implementation.ts"],
4
- "sourcesContent": ["export * as messages from './message'\nexport * as interfaces from './interfaces'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport { isApiError, RuntimeError } from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationLogger,\n IntegrationSpecificClient,\n InterfaceDeclaration,\n InterfaceDeclarationProps,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nexport type GenericZuiSchema<\n A extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>,\n R extends z.ZodTypeAny = z.ZodTypeAny\n> = (typeArguments: A) => R\n\nexport default z\n", "export * as schemas from './schemas'\n\nexport * from './hitl'\nexport * from './llm'\nexport * from './speech-to-text'\nexport * from './sync'\nexport * from './text-to-image'\nexport * from './typing-indicator'\n", "export * as speechToText from './speech-to-text'\n", "import z from '../../zui'\n\nexport const OpenAITranscribeAudioOutputSchema = z.object({\n language: z.string().describe('Detected language of the audio'),\n duration: z.number().describe('Duration of the audio file, in seconds'),\n segments: z.array(\n z.object({\n text: z.string().describe('Text content of the segment.'),\n id: z.number().describe('Unique identifier of the segment'),\n seek: z.number().describe('Seek offset of the segment'),\n start: z.number().describe('Start time of the segment in seconds.'),\n end: z.number().describe('End time of the segment in seconds.'),\n tokens: z.array(z.number()).describe('Array of token IDs for the text content.'),\n temperature: z.number().describe('Temperature parameter used for generating the segment.'),\n avg_logprob: z\n .number()\n .describe('Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.'),\n compression_ratio: z\n .number()\n .describe(\n 'Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.'\n ),\n no_speech_prob: z\n .number()\n .describe(\n 'Probability of no speech in the segment. If the value is higher than 1.0 and the avg_logprob is below -1, consider this segment silent.'\n ),\n })\n ),\n})\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\nimport { ValueOf } from '../type-utils'\nimport { BaseIntegration } from './generic'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\ntype IntegrationContextConfig<TIntegration extends BaseIntegration> =\n | {\n configurationType: null\n configuration: TIntegration['configuration']\n }\n | ValueOf<{\n [TConfigType in keyof TIntegration['configurations']]: {\n configurationType: TConfigType\n configuration: TIntegration['configurations'][TConfigType]\n }\n }>\n\nexport type IntegrationContext<TIntegration extends BaseIntegration = BaseIntegration> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n} & IntegrationContextConfig<TIntegration>\n\nexport const extractContext = <TIntegration extends BaseIntegration>(\n headers: Record<string, string | undefined>\n): IntegrationContext<TIntegration> => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const configurationType = headers[configurationTypeHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n } as IntegrationContext<TIntegration>\n}\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationTypeHeader = 'x-bp-configuration-type'\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "export const unique = <T>(array: T[]): T[] => Array.from(new Set(array))\nexport const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, V][]\nexport const values = <K extends string, V>(obj: Record<K, V>) => Object.values(obj) as V[]\nexport const mapValues = <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R): Record<K, R> =>\n Object.fromEntries(pairs(obj).map(([key, value]) => [key, fn(value, key)])) as Record<K, R>\n\nexport const mergeRecords = <K extends string, V>(\n a: Record<K, V>,\n b: Record<K, V>,\n merge: (v1: V, v2: V) => V\n): Record<K, V> => {\n const keys = unique([...Object.keys(a), ...Object.keys(b)]) as K[]\n const result: Record<K, V> = {} as Record<K, V>\n for (const key of keys) {\n const aValue = a[key]\n const bValue = b[key]\n if (aValue && bValue) {\n result[key] = merge(aValue, bValue)\n } else if (aValue) {\n result[key] = aValue\n } else if (bValue) {\n result[key] = bValue\n }\n }\n return result\n}\n", "import * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema): boolean => {\n return schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { Writable } from '../../type-utils'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport { InterfaceDeclaration, InterfaceResolveInput } from './interface-declaration'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n MessageDefinition,\n InterfaceImplementationStatement,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\ntype InterfaceTypeArguments<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: SchemaStore<TIntegrationEntities>\n) => InterfaceTypeArguments<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly configurations: this['props']['configurations']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public readonly interfaces: Record<string, InterfaceImplementationStatement> = {}\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.configurations = props.configurations\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n\n public clone(\n props: Partial<IntegrationDefinitionProps<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities> {\n const clone = new IntegrationDefinition<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities>({\n ...this,\n ...props,\n })\n for (const [key, value] of Object.entries(this.interfaces)) {\n clone.interfaces[key] = value\n }\n return clone\n }\n\n public extend<E extends BaseEntities>(\n interfaceDeclaration: InterfaceDeclaration<E>,\n builder: ExtensionBuilder<TEntities, E>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.pairs(extensionBuilderOutput).find(([_k, e]) => !isBranded(e))\n if (unbrandedEntity) {\n // this means the user tried providing a plain schema without referencing an entity from the integration\n throw new Error(\n `Cannot extend interface \"${interfaceDeclaration.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const interfaceTypeArguments = utils.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema,\n }))\n\n const { resolved, implementStatement } = interfaceDeclaration.resolve({\n entities: interfaceTypeArguments as InterfaceResolveInput<E>['entities'],\n })\n\n const self = this as Writable<IntegrationDefinition>\n\n /**\n * If an action is defined both in the integration and the interface; we merge both.\n * This allows setting more specific properties in the integration, while staying compatible with the interface.\n * Same goes for channels and events.\n */\n\n self.actions = utils.mergeRecords(self.actions ?? {}, resolved.actions, this._mergeActions)\n self.channels = utils.mergeRecords(self.channels ?? {}, resolved.channels, this._mergeChannels)\n self.events = utils.mergeRecords(self.events ?? {}, resolved.events, this._mergeEvents)\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key =\n entityNames.length === 0 ? interfaceDeclaration.name : `${interfaceDeclaration.name}<${entityNames.join(',')}>`\n this.interfaces[key] = implementStatement\n\n return this\n }\n\n private _mergeActions = (a: ActionDefinition, b: ActionDefinition): ActionDefinition => {\n return {\n ...a,\n ...b,\n input: {\n schema: a.input.schema.merge(b.input.schema),\n },\n output: {\n schema: a.output.schema.merge(b.output.schema),\n },\n }\n }\n\n private _mergeEvents = (a: EventDefinition, b: EventDefinition): EventDefinition => {\n return {\n ...a,\n ...b,\n schema: a.schema.merge(b.schema),\n }\n }\n\n private _mergeChannels = (a: ChannelDefinition, b: ChannelDefinition): ChannelDefinition => {\n const messages = utils.mergeRecords(a.messages, b.messages, this._mergeMessage)\n return {\n ...a,\n ...b,\n messages,\n }\n }\n\n private _mergeMessage = (a: MessageDefinition, b: MessageDefinition): MessageDefinition => {\n return {\n schema: a.schema.merge(b.schema),\n }\n }\n}\n", "import * as utils from '../../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../../zui'\nimport { BaseActions, BaseChannels, BaseEntities, BaseEvents } from './generic'\nimport {\n ActionDefinition,\n ChannelDefinition,\n EntityDefinition,\n EventDefinition,\n InterfaceImplementationStatement,\n ResolvedInterface,\n} from './types'\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n}\n\ntype GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string]\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject> }\n}\n\nexport type InterfaceTemplateNameProps<TEntities extends BaseEntities = BaseEntities> = {\n [K in keyof TEntities]: string\n}\n\nexport type InterfaceDeclarationProps<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels\n> = {\n name: string\n version: string\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n events?: { [K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: (name: string, props: InterfaceTemplateNameProps<TEntities>) => string\n}\n\nexport type InterfaceResolveInput<TEntities extends BaseEntities = BaseEntities> = {\n entities: {\n [K in keyof TEntities]: {\n name: string\n schema: TEntities[K]\n }\n }\n}\n\nexport type InterfaceResolveOutput<\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> = {\n resolved: ResolvedInterface<TActions, TEvents>\n implementStatement: InterfaceImplementationStatement\n}\n\nexport class InterfaceDeclaration<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly entities: NonNullable<this['props']['entities']>\n public readonly events: NonNullable<this['props']['events']>\n public readonly actions: NonNullable<this['props']['actions']>\n public readonly channels: NonNullable<this['props']['channels']>\n public readonly templateName: this['props']['templateName']\n\n public constructor(public readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents>) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as NonNullable<this['props']['entities']>)\n this.events = props.events ?? ({} as NonNullable<this['props']['events']>)\n this.actions = props.actions ?? ({} as NonNullable<this['props']['actions']>)\n this.channels = props.channels ?? ({} as NonNullable<this['props']['channels']>)\n\n this.templateName = props.templateName\n }\n\n public resolve(props: InterfaceResolveInput<TEntities>): InterfaceResolveOutput<TActions, TEvents> {\n const { entities } = props\n\n const implementStatement: InterfaceImplementationStatement = {\n name: this.name,\n version: this.version,\n entities: utils.mapValues(entities, (entity) => ({ name: entity.name })), // { item: { name: 'issue' } }\n actions: {},\n events: {},\n }\n\n const actions: Record<string, ActionDefinition> = {}\n const events: Record<string, EventDefinition> = {}\n const channels: Record<string, ChannelDefinition> = {}\n\n // dereference actions\n for (const [actionName, action] of utils.pairs(this.actions)) {\n const resolvedInputSchema = this._dereference(action.input.schema, entities)\n const resolvedOutputSchema = this._dereference(action.output.schema, entities)\n\n const newActionName = this._rename(entities, actionName)\n actions[newActionName] = {\n ...action,\n input: { schema: resolvedInputSchema },\n output: { schema: resolvedOutputSchema },\n }\n implementStatement.actions[actionName] = { name: newActionName }\n }\n\n // dereference events\n for (const [eventName, event] of utils.pairs(this.events)) {\n const resolvedEventSchema = this._dereference(event.schema, entities)\n const newEventName = this._rename(entities, eventName)\n events[newEventName] = { ...event, schema: resolvedEventSchema }\n implementStatement.events[eventName] = { name: newEventName }\n }\n\n // dereference channels\n for (const [channelName, channel] of utils.pairs(this.channels)) {\n const messages: Record<string, { schema: AnyZodObject }> = {}\n for (const [messageName, message] of utils.pairs(channel.messages)) {\n const resolvedMessageSchema = this._dereference(message.schema, entities)\n messages[messageName] = { ...message, schema: resolvedMessageSchema }\n }\n channels[channelName] = { ...channel, messages }\n }\n\n const resolved = {\n actions: actions as ResolvedInterface<TActions, TEvents>['actions'],\n events: events as ResolvedInterface<TActions, TEvents>['events'],\n channels: channels as ResolvedInterface<TActions, TEvents>['channels'],\n }\n\n return {\n resolved,\n implementStatement,\n }\n }\n\n private _dereference(\n generic: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject>,\n entities: InterfaceResolveInput<TEntities>['entities']\n ): AnyZodObject {\n const entitySchemas: Record<string, AnyZodObject> = {}\n const entityReferences: Record<string, ZodRef> = {}\n for (const [entityName, entity] of utils.pairs(entities)) {\n entitySchemas[entityName] = entity.schema\n entityReferences[entityName] = z.ref(entityName)\n }\n return generic(entityReferences as EntityReferences<TEntities>).dereference(\n entitySchemas as TEntities\n ) as AnyZodObject\n }\n\n private _rename(entities: InterfaceResolveInput<TEntities>['entities'], name: string): string {\n if (!this.templateName) {\n return name\n }\n\n const templateProps = utils.mapValues(entities, (entity) => entity.name) as Record<keyof TEntities, string>\n return this.templateName(name, templateProps)\n }\n}\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext<TIntegration>(req.headers)\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<TIntegration>(vanillaClient)\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (thrown) {\n if (isApiError(thrown)) {\n const runtimeError = new RuntimeError(thrown.message, thrown)\n integrationLogger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(thrown)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n integrationLogger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n }\n\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly _client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this._client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this._client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this._client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this._client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this._client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this._client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this._client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this._client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this._client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this._client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this._client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this._client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this._client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this._client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this._client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this._client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this._client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this._client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this._client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this._client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this._client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this._client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this._client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this._client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this._client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this._client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this._client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this._client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this._client.configureIntegration(x)\n\n public uploadFile: routes.UploadFile<TIntegration> = (x) => this._client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TIntegration> = (x) => this._client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TIntegration> = (x) => this._client.deleteFile(x)\n public listFiles: routes.ListFiles<TIntegration> = (x) => this._client.listFiles(x)\n public getFile: routes.GetFile<TIntegration> = (x) => this._client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TIntegration> = (x) => this._client.updateFileMetadata(x)\n}\n", "import util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { InterfaceDeclaration } from '../integration'\nimport * as messages from '../message'\nimport z, { AnyZodObject } from '../zui'\n\nconst withUserId = <S extends z.AnyZodObject>(s: { schema: S }) => ({\n ...s,\n schema: () =>\n s.schema.extend({\n userId: z.string().optional().describe('Allows sending a message pretending to be a certain user'),\n }),\n})\n\nconst messageSourceSchema = z.union([\n z.object({ type: z.literal('user'), userId: z.string() }),\n z.object({ type: z.literal('bot') }),\n])\n\ntype Tuple<T> = [T, T, ...T[]]\nconst messagePayloadSchemas: AnyZodObject[] = Object.entries(messages.defaults).map(([k, v]) =>\n z.object({\n source: messageSourceSchema,\n type: z.literal(k),\n payload: v.schema,\n })\n)\n\nconst messageSchema = z.union(messagePayloadSchemas as Tuple<AnyZodObject>)\n\nexport const hitl = new InterfaceDeclaration({\n name: 'hitl',\n version: '0.4.0',\n entities: {},\n events: {\n hitlAssigned: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n userId: z.string(),\n }),\n },\n hitlStopped: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n }),\n },\n },\n actions: {\n createUser: {\n input: {\n schema: () =>\n z.object({\n name: z.string().optional(),\n pictureUrl: z.string().optional(),\n email: z.string().optional(),\n }),\n },\n output: {\n schema: () =>\n z.object({\n userId: z.string(),\n }),\n },\n },\n startHitl: {\n input: {\n schema: () =>\n z.object({\n userId: z.string(),\n title: z.string(),\n description: z.string().optional(),\n messageHistory: z\n .array(messageSchema)\n .optional()\n .describe('Message history to display in the HITL session'),\n }),\n },\n output: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n }),\n },\n },\n stopHitl: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n reason: z.enum(['timeout', 'cancel']).optional(),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n channels: {\n hitl: {\n messages: {\n text: withUserId(messages.defaults.text),\n },\n },\n },\n})\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst ToolCallSchema = z.object({\n id: z.string(),\n type: z.enum(['function']),\n function: z.object({\n name: z.string(),\n arguments: z\n .record(z.any())\n .nullable()\n .describe('Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.'),\n }),\n})\n\nconst ToolChoiceSchema = z.object({\n // TODO: remove empty value from enum once Studio issue is fixed\n type: z.enum(['auto', 'specific', 'any', 'none', '']).optional(), // note: Claude doesn't support \"none\" but we can simply strip out the tools when `type` is \"none\"\n functionName: z.string().optional().describe('Required if `type` is \"specific\"'),\n})\n\nconst MessageSchema = z.object({\n role: z.enum(['user', 'assistant']),\n type: z.enum(['text', 'tool_calls', 'tool_result', 'multipart']).default('text'),\n toolCalls: z.array(ToolCallSchema).optional().describe('Required if `type` is \"tool_calls\"'),\n toolResultCallId: z.string().optional().describe('Required if `type` is \"tool_result\"'), // note: not supported by Gemini\n content: z\n .string()\n // TODO: union types are not supported yet by the Studio, comment this out when testing via an action card in the Studio\n .or(\n z.array(\n z.object({\n type: z.enum(['text', 'image']),\n mimeType: z\n .string()\n .optional()\n .describe(\n 'Indicates the MIME type of the content. If not provided it will be detected from the content-type header of the provided URL.'\n ),\n text: z.string().optional().describe('Required if part type is \"text\" '),\n url: z.string().optional().describe('Required if part type is \"image\"'),\n })\n )\n )\n .optional()\n .nullable()\n .describe(\n 'Required unless `type` is \"tool_call\". If `type` is \"multipart\", this field must be an array of content objects. If `type` is \"tool_result\" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is \"tool_call\" then the `toolCalls` field should be used instead.'\n ),\n})\n\nconst ModelRefSchema = z.object({ id: z.string() })\n\nconst ModelSchema = ModelRefSchema.extend({\n name: z.string(),\n description: z.string(),\n tags: z.array(\n z.enum([\n 'recommended',\n 'deprecated',\n 'general-purpose',\n 'low-cost',\n 'vision',\n 'coding',\n 'agents',\n 'function-calling',\n 'roleplay',\n 'storytelling',\n ])\n ),\n input: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n output: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n})\n\nconst GenerateContentInputSchema = <S extends z.ZodSchema>(modelRefSchema: S) =>\n z.object({\n model: modelRefSchema.describe('Model to use for content generation').optional(),\n systemPrompt: z.string().optional().describe('Optional system prompt to guide the model'),\n messages: z.array(MessageSchema).describe('Array of messages for the model to process'),\n responseFormat: z\n .enum(['text', 'json_object'])\n .optional()\n .describe(\n 'Response format expected from the model. If \"json_object\" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'\n ), // note: only OpenAI and Groq support this but for other models we can just append this as an indication in the system prompt\n // note: we don't support streaming yet\n maxTokens: z.number().optional().describe('Maximum number of tokens allowed in the generated response'),\n temperature: z\n .number()\n .min(0)\n .max(2)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .default(1)\n .describe('Sampling temperature for the model. Higher values result in more random outputs.'),\n topP: z\n .number()\n .min(0)\n .max(1)\n .default(1)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .describe(\n 'Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold.'\n ), // TODO: .placeholder() from zui doesn't work, so we have to use .default() which introduces some typing issues\n // note: topK is supported by Claude and Gemini but not by OpenAI or Groq\n stopSequences: z\n .array(z.string())\n .max(4)\n .optional()\n .describe('Sequences where the model should stop generating further tokens.'),\n tools: z\n .array(\n z.object({\n type: z.literal('function'),\n function: z.object({\n name: z.string().describe('Function name'),\n description: z.string().optional(),\n argumentsSchema: z.object({}).passthrough().optional().describe('JSON schema of the function arguments'),\n }),\n })\n )\n .optional(),\n // TODO: an object with options doesn't seem to be supported by the Studio as it's not rendering correctly, the dropdown for \"type\" is not working and it's sending a blank value instead which causes a schema validation error unless an empty value is allowed in the `type` enum\n toolChoice: ToolChoiceSchema.optional(), // note: Gemini doesn't support this but we can just ignore it there\n userId: z.string().optional(),\n debug: z.boolean().optional().describe('Set to `true` to output debug information to the bot logs'),\n })\n\nconst GenerateContentInputBaseSchema = GenerateContentInputSchema(ModelRefSchema)\n\nconst GenerateContentOutputSchema = z.object({\n id: z.string().describe('Response ID from LLM provider'),\n provider: z.string().describe('LLM provider name'),\n model: z.string().describe('Model name'),\n choices: z.array(\n MessageSchema.omit({ role: true }).extend({\n role: z.literal('assistant'),\n index: z.number().int(),\n stopReason: z.enum(['stop', 'max_tokens', 'tool_calls', 'content_filter', 'other']),\n // note: stopSequence is supported by Claude but not by OpenAI, Groq or Gemini\n })\n ),\n usage: z.object({\n inputTokens: z.number().int().describe('Number of input tokens used by the model'),\n inputCost: z.number().describe('Cost of the input tokens received by the model, in U.S. dollars'),\n outputTokens: z.number().int().describe('Number of output tokens used by the model'),\n outputCost: z.number().describe('Cost of the output tokens generated by the model, in U.S. dollars'),\n }),\n botpress: z.object({\n cost: z.number().describe('Total cost of the content generation, in U.S. dollars'),\n }),\n})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '5.0.0',\n entities: {\n modelRef: {\n schema: ModelRefSchema,\n },\n },\n events: {},\n actions: {\n generateContent: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ modelRef }) => GenerateContentInputSchema(modelRef),\n },\n output: {\n schema: () => GenerateContentOutputSchema,\n },\n },\n listLanguageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ modelRef }) =>\n z.object({\n models: z.array(z.intersection(ModelSchema, modelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace llm {\n export type GenerateContentInput = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateContentOutput = z.infer<typeof GenerateContentOutputSchema>\n export type ToolCall = z.infer<typeof ToolCallSchema>\n export type Message = z.infer<typeof MessageSchema>\n export type Model = z.infer<typeof ModelSchema>\n export type ModelDetails = Omit<Model, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\nimport { OpenAITranscribeAudioOutputSchema } from './schemas/speech-to-text'\n\nconst SpeechModelRefSchema = z.object({\n id: z.string(),\n})\n\nconst SpeechToTextModelSchema = SpeechModelRefSchema.extend({\n name: z.string(),\n costPerMinute: z.number().describe('Cost per minute of speech transcription, in U.S. dollars'),\n})\n\nconst TranscribeAudioInputSchema = <TModelRef extends z.ZodSchema>(imageModelRefSchema: TModelRef) =>\n z.object({\n model: imageModelRefSchema.optional().describe('Model to use for speech-to-text transcription (optional)'),\n fileUrl: z\n .string()\n .url()\n .describe(\n 'URL of the audio file to transcribe. The URL should return a content-type header in order to detect the audio format. Supported audio formats supported are: mp3, mp4, mpeg, mpga, m4a, wav, webm'\n ),\n language: z\n .string()\n .optional()\n .describe(\n 'The language of the input audio (optional). Supplying the input language in ISO-639-1 format will improve accuracy and latency.'\n ),\n prompt: z\n .string()\n .optional()\n .describe(\n \"An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.\"\n ),\n temperature: z\n .number()\n .default(0)\n .optional()\n .describe(\n 'The sampling temperature (optional), between 0 and 1. Defaults to 0 (automatic). Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.'\n ),\n })\n\nconst TranscribeAudioBaseSchema = TranscribeAudioInputSchema(SpeechModelRefSchema)\n\nconst TranscribeAudioOutputSchema = OpenAITranscribeAudioOutputSchema.extend({\n model: z.string().describe('Model name used'),\n cost: z.number().describe('Total cost of the transcription, in U.S. dollars (DEPRECATED)'),\n botpress: z.object({\n cost: z.number().describe('Total cost of the transcription, in U.S. dollars'),\n }),\n})\n\nexport const speechToText = new InterfaceDeclaration({\n name: 'speechToText',\n version: '2.0.0',\n entities: {\n speechToTextModelRef: {\n schema: SpeechModelRefSchema,\n },\n },\n actions: {\n transcribeAudio: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ speechToTextModelRef }) => TranscribeAudioInputSchema(speechToTextModelRef),\n },\n output: {\n schema: () => TranscribeAudioOutputSchema,\n },\n },\n listSpeechToTextModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ speechToTextModelRef }) =>\n z.object({\n models: z.array(z.intersection(SpeechToTextModelSchema, speechToTextModelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace speechToText {\n export type TranscribeAudioInputSchema = z.infer<typeof TranscribeAudioBaseSchema>\n export type TranscribeAudioOutputSchema = z.infer<typeof TranscribeAudioOutputSchema>\n export type SpeechToTextModel = z.infer<typeof SpeechToTextModelSchema>\n export type SpeechToTextModelDetails = Omit<SpeechToTextModel, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst baseItem = z.object({ id: z.string() })\nconst withId = (schema: z.ZodTypeAny) => z.intersection(schema, baseItem)\n\nconst capitalize = (s: string) => s[0]!.toUpperCase() + s.slice(1)\nconst camelCase = (...parts: string[]) => {\n const [first, ...rest] = parts.filter((s) => s.length > 0).map((s) => s.toLowerCase())\n if (!first) {\n return ''\n }\n return [first, ...rest.map(capitalize)].join('')\n}\n\nconst nextToken = z.string().optional()\nexport const listable = new InterfaceDeclaration({\n name: 'listable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n list: {\n input: {\n schema: () => z.object({ nextToken }),\n },\n output: {\n schema: (args) =>\n z.object({\n items: z.array(withId(args.item)),\n meta: z.object({ nextToken }),\n }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueList\n})\n\nexport const creatable = new InterfaceDeclaration({\n name: 'creatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n created: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n create: {\n input: {\n schema: (args) => z.object({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueCreate, issueCreated\n})\n\nexport const readable = new InterfaceDeclaration({\n name: 'readable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n read: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueRead\n})\n\nexport const updatable = new InterfaceDeclaration({\n name: 'updatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n updated: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n update: {\n input: {\n schema: (args) => baseItem.extend({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueUpdate, issueUpdated\n})\n\nexport const deletable = new InterfaceDeclaration({\n name: 'deletable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n deleted: {\n schema: () => baseItem,\n },\n },\n actions: {\n delete: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueDelete, issueDeleted\n})\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst ImageModelRefSchema = z.object({\n id: z.string(),\n})\n\nconst ImageModelSchema = ImageModelRefSchema.extend({\n name: z.string(),\n costPerImage: z.number().describe('Cost per image generation, in U.S. dollars'),\n sizes: z.array(z.string()).describe('Available image sizes'),\n defaultSize: z.string().describe('Default image size generated by model'),\n})\n\nconst ImageGenerationParamsSchema = z.object({}).describe('Model-specific parameters for image generation')\n\nconst GenerateImageInputSchema = <TModelRef extends z.ZodSchema, TParams extends z.ZodSchema>(\n imageModelRefSchema: TModelRef,\n paramsSchema: TParams\n) =>\n z.object({\n model: imageModelRefSchema.optional().describe('Model to use for image generation'),\n prompt: z.string(),\n size: z.string().optional(),\n expiration: z\n .number()\n .int()\n .min(30)\n .max(90)\n .optional()\n .describe(\n 'Expiration of the generated image in days, after which the image will be automatically deleted to free up storage space in your account. The default is to keep the image indefinitely (no expiration). The minimum is 30 days and the maximum is 90 days.'\n ),\n params: paramsSchema.optional(),\n })\n\nconst GenerateContentInputBaseSchema = GenerateImageInputSchema(ImageModelRefSchema, ImageGenerationParamsSchema)\n\nconst GenerateImageOutputSchema = z.object({\n model: z.string().describe('Model name used'),\n imageUrl: z.string().describe('Temporary URL of generated image'),\n cost: z.number().describe('Cost of the image generation, in U.S. dollars (DEPRECATED)'),\n botpress: z.object({\n cost: z.number().describe('Cost of the image generation, in U.S. dollars'),\n }),\n})\n\nexport const textToImage = new InterfaceDeclaration({\n name: 'textToImage',\n version: '2.1.0',\n entities: {\n imageModelRef: {\n schema: ImageModelRefSchema,\n },\n imageGenerationParams: {\n schema: ImageGenerationParamsSchema,\n },\n },\n actions: {\n generateImage: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ imageModelRef, imageGenerationParams }) =>\n GenerateImageInputSchema(imageModelRef, imageGenerationParams),\n },\n output: {\n schema: () => GenerateImageOutputSchema,\n },\n },\n listImageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ imageModelRef }) =>\n z.object({\n models: z.array(z.intersection(ImageModelSchema, imageModelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace textToImage {\n export type GenerateImageInputSchema = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateImageOutputSchema = z.infer<typeof GenerateImageOutputSchema>\n export type ImageModel = z.infer<typeof ImageModelSchema>\n export type ImageModelDetails = Omit<ImageModel, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration'\nimport z from '../zui'\n\nexport const typingIndicator = new InterfaceDeclaration({\n name: 'typingIndicator',\n version: '0.0.1',\n entities: {},\n events: {},\n actions: {\n startTypingIndicator: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n messageId: z.string().describe('The message ID to which the typing indicator should be attached'),\n timeout: z\n .number()\n .optional()\n .describe('The timeout in milliseconds after which the typing indicator should stop'),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n stopTypingIndicator: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n messageId: z.string().describe('The message ID from which the typing indicator should be removed'),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n})\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<TBot>(vanillaClient)\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly _client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this._client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this._client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this._client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this._client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this._client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this._client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this._client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this._client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this._client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this._client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) =>\n this._client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this._client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this._client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) =>\n this._client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this._client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) =>\n this._client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this._client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this._client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this._client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this._client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this._client\n .getState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this._client\n .setState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this._client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this._client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this._client.callAction(x)\n\n public uploadFile: routes.UploadFile<TBot> = (x) => this._client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TBot> = (x) => this._client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TBot> = (x) => this._client.deleteFile(x)\n public listFiles: routes.ListFiles<TBot> = (x) => this._client.listFiles(x)\n public getFile: routes.GetFile<TBot> = (x) => this._client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TBot> = (x) => this._client.updateFileMetadata(x)\n public searchFiles: routes.SearchFiles<TBot> = (x) => this._client.searchFiles(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this._client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this._client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this._client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this._client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<TIntegrations[K]>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
- "mappings": "onBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,eAAAC,GAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,GAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,ICAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,IAAAC,GAAkB,2BAClBC,EAAAJ,EAAc,4BAOd,IAAOE,EAAQ,KDNf,IAAMG,EAAiB,I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,OAAAL,EACA,IAAAb,EACA,GAAGoB,CACL,CAAC,CACH,CACF,CACJ,CACF,EG/DO,IAAMC,EAAN,KAIL,CACQ,OAAoD,CAC1D,gBAAiB,CAAC,EAClB,cAAe,CAAC,EAChB,qBAAsB,CAAC,CACzB,EAEgB,MAET,YAAYC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,GAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
4
+ "sourcesContent": ["export * as messages from './message'\nexport * as interfaces from './interfaces'\nexport * from './const'\nexport * from './serve'\nexport * from './zui'\n\nexport { isApiError, RuntimeError } from '@botpress/client'\n\nexport {\n IntegrationDefinition,\n IntegrationDefinitionProps,\n IntegrationImplementation as Integration,\n IntegrationImplementationProps as IntegrationProps,\n IntegrationContext,\n IntegrationLogger,\n IntegrationSpecificClient,\n InterfaceDeclaration,\n InterfaceDeclarationProps,\n TagDefinition,\n ConfigurationDefinition,\n AdditionalConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n MessageDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n} from './integration'\n\nexport { Bot, BotProps, BotContext, BotSpecificClient, IntegrationInstance } from './bot'\n", "import { z } from './zui'\n\nconst NonEmptyString = z.string().min(1)\n\nconst textMessageSchema = z.object({\n text: NonEmptyString,\n})\n\nconst markdownMessageSchema = z.object({\n markdown: NonEmptyString,\n})\n\nconst imageMessageSchema = z.object({\n imageUrl: NonEmptyString,\n})\n\nconst audioMessageSchema = z.object({\n audioUrl: NonEmptyString,\n})\n\nconst videoMessageSchema = z.object({\n videoUrl: NonEmptyString,\n})\n\nconst fileMessageSchema = z.object({\n fileUrl: NonEmptyString,\n title: NonEmptyString.optional(),\n})\n\nconst locationMessageSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n address: z.string().optional(),\n title: z.string().optional(),\n})\n\nconst cardSchema = z.object({\n title: NonEmptyString,\n subtitle: NonEmptyString.optional(),\n imageUrl: NonEmptyString.optional(),\n actions: z.array(\n z.object({\n action: z.enum(['postback', 'url', 'say']),\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst choiceSchema = z.object({\n text: NonEmptyString,\n options: z.array(\n z.object({\n label: NonEmptyString,\n value: NonEmptyString,\n })\n ),\n})\n\nconst carouselSchema = z.object({\n items: z.array(cardSchema),\n})\n\nconst blocSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('text'), payload: textMessageSchema }),\n z.object({ type: z.literal('markdown'), payload: markdownMessageSchema }),\n z.object({ type: z.literal('image'), payload: imageMessageSchema }),\n z.object({ type: z.literal('audio'), payload: audioMessageSchema }),\n z.object({ type: z.literal('video'), payload: videoMessageSchema }),\n z.object({ type: z.literal('file'), payload: fileMessageSchema }),\n z.object({ type: z.literal('location'), payload: locationMessageSchema }),\n])\n\nconst blocsSchema = z.object({\n items: z.array(blocSchema),\n})\n\nexport const defaults = {\n text: { schema: textMessageSchema },\n markdown: { schema: markdownMessageSchema },\n image: { schema: imageMessageSchema },\n audio: { schema: audioMessageSchema },\n video: { schema: videoMessageSchema },\n file: { schema: fileMessageSchema },\n location: { schema: locationMessageSchema },\n carousel: { schema: carouselSchema },\n card: { schema: cardSchema },\n dropdown: { schema: choiceSchema },\n choice: { schema: choiceSchema },\n bloc: { schema: blocsSchema },\n} as const // should use satisfies operator but this works for older versions of TS\n", "import { z } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nexport type GenericZuiSchema<\n A extends Record<string, z.ZodTypeAny> = Record<string, z.ZodTypeAny>,\n R extends z.ZodTypeAny = z.ZodTypeAny\n> = (typeArguments: A) => R\n\nexport default z\n", "export * as schemas from './schemas'\n\nexport * from './hitl'\nexport * from './llm'\nexport * from './speech-to-text'\nexport * from './sync'\nexport * from './text-to-image'\nexport * from './typing-indicator'\n", "export * as speechToText from './speech-to-text'\n", "import z from '../../zui'\n\nexport const OpenAITranscribeAudioOutputSchema = z.object({\n language: z.string().describe('Detected language of the audio'),\n duration: z.number().describe('Duration of the audio file, in seconds'),\n segments: z.array(\n z.object({\n text: z.string().describe('Text content of the segment.'),\n id: z.number().describe('Unique identifier of the segment'),\n seek: z.number().describe('Seek offset of the segment'),\n start: z.number().describe('Start time of the segment in seconds.'),\n end: z.number().describe('End time of the segment in seconds.'),\n tokens: z.array(z.number()).describe('Array of token IDs for the text content.'),\n temperature: z.number().describe('Temperature parameter used for generating the segment.'),\n avg_logprob: z\n .number()\n .describe('Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.'),\n compression_ratio: z\n .number()\n .describe(\n 'Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.'\n ),\n no_speech_prob: z\n .number()\n .describe(\n 'Probability of no speech in the segment. If the value is higher than 1.0 and the avg_logprob is below -1, consider this segment silent.'\n ),\n })\n ),\n})\n", "import { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n configurationTypeHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\nimport { ValueOf } from '../type-utils'\nimport { BaseIntegration } from './generic'\n\nexport const integrationOperationSchema = z.enum([\n 'webhook_received',\n 'message_created',\n 'action_triggered',\n 'register',\n 'unregister',\n 'ping',\n 'create_user',\n 'create_conversation',\n])\n\nexport type IntegrationOperation = z.infer<typeof integrationOperationSchema>\n\ntype IntegrationContextConfig<TIntegration extends BaseIntegration> =\n | {\n configurationType: null\n configuration: TIntegration['configuration']\n }\n | ValueOf<{\n [TConfigType in keyof TIntegration['configurations']]: {\n configurationType: TConfigType\n configuration: TIntegration['configurations'][TConfigType]\n }\n }>\n\nexport type IntegrationContext<TIntegration extends BaseIntegration = BaseIntegration> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n} & IntegrationContextConfig<TIntegration>\n\nexport const extractContext = <TIntegration extends BaseIntegration>(\n headers: Record<string, string | undefined>\n): IntegrationContext<TIntegration> => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\n const configurationType = headers[configurationTypeHeader]\n const base64Configuration = headers[configurationHeader]\n const operation = integrationOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!botUserId) {\n throw new Error('Missing bot user headers')\n }\n\n if (!integrationId) {\n throw new Error('Missing integration headers')\n }\n\n if (!webhookId) {\n throw new Error('Missing webhook headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n botUserId,\n integrationId,\n webhookId,\n operation,\n configurationType: configurationType ?? null,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n } as IntegrationContext<TIntegration>\n}\n", "export const botIdHeader = 'x-bot-id'\nexport const botUserIdHeader = 'x-bot-user-id'\nexport const integrationIdHeader = 'x-integration-id'\nexport const webhookIdHeader = 'x-webhook-id'\n\nexport const configurationTypeHeader = 'x-bp-configuration-type'\nexport const configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\n", "export const unique = <T>(array: T[]): T[] => Array.from(new Set(array))\nexport const pairs = <K extends string, V>(obj: Record<K, V>) => Object.entries(obj) as [K, V][]\nexport const values = <K extends string, V>(obj: Record<K, V>) => Object.values(obj) as V[]\nexport const mapValues = <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R): Record<K, R> =>\n Object.fromEntries(pairs(obj).map(([key, value]) => [key, fn(value, key)])) as Record<K, R>\n\nexport const mergeRecords = <K extends string, V>(\n a: Record<K, V>,\n b: Record<K, V>,\n merge: (v1: V, v2: V) => V\n): Record<K, V> => {\n const keys = unique([...Object.keys(a), ...Object.keys(b)]) as K[]\n const result: Record<K, V> = {} as Record<K, V>\n for (const key of keys) {\n const aValue = a[key]\n const bValue = b[key]\n if (aValue && bValue) {\n result[key] = merge(aValue, bValue)\n } else if (aValue) {\n result[key] = aValue\n } else if (bValue) {\n result[key] = bValue\n }\n }\n return result\n}\n", "import * as utils from '../../utils'\nimport { z } from '../../zui'\n\nconst schemaName = Symbol('schemaName')\n\ntype BaseSchemas = Record<string, z.ZodSchema>\n\nexport type SchemaStoreProps<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: {\n schema: TSchemas[K]\n }\n}\n\nexport type BrandedSchema<TSchema extends BaseSchemas[string] = BaseSchemas[string]> = {\n schema: TSchema\n [schemaName]: string\n}\n\nexport type SchemaStore<TSchemas extends BaseSchemas = BaseSchemas> = {\n [K in keyof TSchemas]: BrandedSchema<TSchemas[K]>\n}\n\nexport const createStore = <TSchemas extends BaseSchemas>(\n props: SchemaStoreProps<TSchemas> | undefined\n): SchemaStore<TSchemas> => {\n if (!props) {\n return {} as SchemaStore<TSchemas>\n }\n const store: SchemaStore<BaseSchemas> = utils.mapValues(props, (e, k) => ({ ...e, [schemaName]: k }))\n return store as SchemaStore<TSchemas>\n}\n\nexport const isBranded = (schema: BrandedSchema): boolean => {\n return schema[schemaName] !== undefined\n}\n\nexport const getName = (schema: BrandedSchema): string => {\n return schema[schemaName]\n}\n", "import { Writable } from '../../type-utils'\nimport * as utils from '../../utils'\nimport { z } from '../../zui'\nimport { SchemaStore, BrandedSchema, createStore, isBranded, getName } from './branded-schema'\nimport { BaseConfig, BaseEvents, BaseActions, BaseChannels, BaseStates, BaseEntities, BaseConfigs } from './generic'\nimport { InterfaceDeclaration, InterfaceResolveInput } from './interface-declaration'\nimport {\n ConfigurationDefinition,\n EventDefinition,\n ChannelDefinition,\n ActionDefinition,\n StateDefinition,\n UserDefinition,\n SecretDefinition,\n EntityDefinition,\n MessageDefinition,\n InterfaceImplementationStatement,\n AdditionalConfigurationDefinition,\n} from './types'\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> = {\n name: string\n version: string\n\n title?: string\n description?: string\n icon?: string\n readme?: string\n\n identifier?: {\n extractScript?: string\n fallbackHandlerScript?: string\n }\n\n configuration?: ConfigurationDefinition<TConfig>\n configurations?: {\n [K in keyof TConfigs]: AdditionalConfigurationDefinition<TConfigs[K]>\n }\n\n events?: { [K in keyof TEvents]: EventDefinition<TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: ActionDefinition<TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: ChannelDefinition<TChannels[K]>\n }\n\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n\n user?: UserDefinition\n\n secrets?: Record<string, SecretDefinition>\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n}\n\ntype InterfaceTypeArguments<TInterfaceEntities extends BaseEntities> = {\n [K in keyof TInterfaceEntities]: BrandedSchema<z.ZodSchema<z.infer<TInterfaceEntities[K]>>>\n}\n\ntype ExtensionBuilder<TIntegrationEntities extends BaseEntities, TInterfaceEntities extends BaseEntities> = (\n input: SchemaStore<TIntegrationEntities>\n) => InterfaceTypeArguments<TInterfaceEntities>\n\nexport class IntegrationDefinition<\n TConfig extends BaseConfig = BaseConfig,\n TConfigs extends BaseConfigs = BaseConfigs,\n TEvents extends BaseEvents = BaseEvents,\n TActions extends BaseActions = BaseActions,\n TChannels extends BaseChannels = BaseChannels,\n TStates extends BaseStates = BaseStates,\n TEntities extends BaseEntities = BaseEntities\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly title: this['props']['title']\n public readonly description: this['props']['description']\n public readonly icon: this['props']['icon']\n public readonly readme: this['props']['readme']\n public readonly configuration: this['props']['configuration']\n public readonly configurations: this['props']['configurations']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\n public readonly channels: this['props']['channels']\n public readonly states: this['props']['states']\n public readonly user: this['props']['user']\n public readonly secrets: this['props']['secrets']\n public readonly identifier: this['props']['identifier']\n public readonly entities: this['props']['entities']\n\n public readonly interfaces: Record<string, InterfaceImplementationStatement> = {}\n\n public constructor(\n public readonly props: IntegrationDefinitionProps<\n TConfig,\n TConfigs,\n TEvents,\n TActions,\n TChannels,\n TStates,\n TEntities\n >\n ) {\n this.name = props.name\n this.version = props.version\n this.icon = props.icon\n this.readme = props.readme\n this.title = props.title\n this.identifier = props.identifier\n this.description = props.description\n this.configuration = props.configuration\n this.configurations = props.configurations\n this.events = props.events\n this.actions = props.actions\n this.channels = props.channels\n this.states = props.states\n this.user = props.user\n this.secrets = props.secrets\n this.entities = props.entities\n }\n\n public clone(\n props: Partial<IntegrationDefinitionProps<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities> {\n const clone = new IntegrationDefinition<TConfig, TConfigs, TEvents, TActions, TChannels, TStates, TEntities>({\n ...this,\n ...props,\n })\n for (const [key, value] of Object.entries(this.interfaces)) {\n clone.interfaces[key] = value\n }\n return clone\n }\n\n public extend<E extends BaseEntities>(\n interfaceDeclaration: InterfaceDeclaration<E>,\n builder: ExtensionBuilder<TEntities, E>\n ): this {\n const extensionBuilderOutput = builder(createStore(this.entities))\n const unbrandedEntity = utils.pairs(extensionBuilderOutput).find(([_k, e]) => !isBranded(e))\n if (unbrandedEntity) {\n // this means the user tried providing a plain schema without referencing an entity from the integration\n throw new Error(\n `Cannot extend interface \"${interfaceDeclaration.name}\" with entity \"${unbrandedEntity[0]}\"; the provided schema is not part of the integration's entities.`\n )\n }\n\n const interfaceTypeArguments = utils.mapValues(extensionBuilderOutput, (e) => ({\n name: getName(e),\n schema: e.schema,\n }))\n\n const { resolved, implementStatement } = interfaceDeclaration.resolve({\n entities: interfaceTypeArguments as InterfaceResolveInput<E>['entities'],\n })\n\n const self = this as Writable<IntegrationDefinition>\n\n /**\n * If an action is defined both in the integration and the interface; we merge both.\n * This allows setting more specific properties in the integration, while staying compatible with the interface.\n * Same goes for channels and events.\n */\n\n self.actions = utils.mergeRecords(self.actions ?? {}, resolved.actions, this._mergeActions)\n self.channels = utils.mergeRecords(self.channels ?? {}, resolved.channels, this._mergeChannels)\n self.events = utils.mergeRecords(self.events ?? {}, resolved.events, this._mergeEvents)\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n\n const key =\n entityNames.length === 0 ? interfaceDeclaration.name : `${interfaceDeclaration.name}<${entityNames.join(',')}>`\n this.interfaces[key] = implementStatement\n\n return this\n }\n\n private _mergeActions = (a: ActionDefinition, b: ActionDefinition): ActionDefinition => {\n return {\n ...a,\n ...b,\n input: {\n schema: a.input.schema.merge(b.input.schema),\n },\n output: {\n schema: a.output.schema.merge(b.output.schema),\n },\n }\n }\n\n private _mergeEvents = (a: EventDefinition, b: EventDefinition): EventDefinition => {\n return {\n ...a,\n ...b,\n schema: a.schema.merge(b.schema),\n }\n }\n\n private _mergeChannels = (a: ChannelDefinition, b: ChannelDefinition): ChannelDefinition => {\n const messages = utils.mergeRecords(a.messages, b.messages, this._mergeMessage)\n return {\n ...a,\n ...b,\n messages,\n }\n }\n\n private _mergeMessage = (a: MessageDefinition, b: MessageDefinition): MessageDefinition => {\n return {\n schema: a.schema.merge(b.schema),\n }\n }\n}\n", "import * as utils from '../../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../../zui'\nimport { BaseActions, BaseChannels, BaseEntities, BaseEvents } from './generic'\nimport {\n ActionDefinition,\n ChannelDefinition,\n EntityDefinition,\n EventDefinition,\n InterfaceImplementationStatement,\n ResolvedInterface,\n} from './types'\n\ntype EntityReferences<TEntities extends BaseEntities> = {\n [K in keyof TEntities]: ZodRef\n}\n\ntype GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>\n}\n\ntype GenericChannelDefinition<\n TEntities extends BaseEntities,\n TChannel extends BaseChannels[string] = BaseChannels[string]\n> = {\n messages: {\n [K in keyof TChannel]: {\n schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>\n }\n }\n}\n\ntype GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\n billable?: boolean\n cacheable?: boolean\n input: { schema: GenericZuiSchema<EntityReferences<TEntities>, TAction> }\n output: { schema: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject> }\n}\n\nexport type InterfaceTemplateNameProps<TEntities extends BaseEntities = BaseEntities> = {\n [K in keyof TEntities]: string\n}\n\nexport type InterfaceDeclarationProps<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEntities = BaseEntities,\n TChannels extends BaseChannels = BaseChannels\n> = {\n name: string\n version: string\n\n entities?: {\n [K in keyof TEntities]: EntityDefinition<TEntities[K]>\n }\n\n events?: { [K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]> }\n\n actions?: {\n [K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>\n }\n\n channels?: {\n [K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>\n }\n\n templateName?: (name: string, props: InterfaceTemplateNameProps<TEntities>) => string\n}\n\nexport type InterfaceResolveInput<TEntities extends BaseEntities = BaseEntities> = {\n entities: {\n [K in keyof TEntities]: {\n name: string\n schema: TEntities[K]\n }\n }\n}\n\nexport type InterfaceResolveOutput<\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> = {\n resolved: ResolvedInterface<TActions, TEvents>\n implementStatement: InterfaceImplementationStatement\n}\n\nexport class InterfaceDeclaration<\n TEntities extends BaseEntities = BaseEntities,\n TActions extends BaseActions = BaseActions,\n TEvents extends BaseEvents = BaseEvents\n> {\n public readonly name: this['props']['name']\n public readonly version: this['props']['version']\n public readonly entities: NonNullable<this['props']['entities']>\n public readonly events: NonNullable<this['props']['events']>\n public readonly actions: NonNullable<this['props']['actions']>\n public readonly channels: NonNullable<this['props']['channels']>\n public readonly templateName: this['props']['templateName']\n\n public constructor(public readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents>) {\n this.name = props.name\n this.version = props.version\n this.entities = props.entities ?? ({} as NonNullable<this['props']['entities']>)\n this.events = props.events ?? ({} as NonNullable<this['props']['events']>)\n this.actions = props.actions ?? ({} as NonNullable<this['props']['actions']>)\n this.channels = props.channels ?? ({} as NonNullable<this['props']['channels']>)\n\n this.templateName = props.templateName\n }\n\n public resolve(props: InterfaceResolveInput<TEntities>): InterfaceResolveOutput<TActions, TEvents> {\n const { entities } = props\n\n const implementStatement: InterfaceImplementationStatement = {\n name: this.name,\n version: this.version,\n entities: utils.mapValues(entities, (entity) => ({ name: entity.name })), // { item: { name: 'issue' } }\n actions: {},\n events: {},\n }\n\n const actions: Record<string, ActionDefinition> = {}\n const events: Record<string, EventDefinition> = {}\n const channels: Record<string, ChannelDefinition> = {}\n\n // dereference actions\n for (const [actionName, action] of utils.pairs(this.actions)) {\n const resolvedInputSchema = this._dereference(action.input.schema, entities)\n const resolvedOutputSchema = this._dereference(action.output.schema, entities)\n\n const newActionName = this._rename(entities, actionName)\n actions[newActionName] = {\n ...action,\n input: { schema: resolvedInputSchema },\n output: { schema: resolvedOutputSchema },\n }\n implementStatement.actions[actionName] = { name: newActionName }\n }\n\n // dereference events\n for (const [eventName, event] of utils.pairs(this.events)) {\n const resolvedEventSchema = this._dereference(event.schema, entities)\n const newEventName = this._rename(entities, eventName)\n events[newEventName] = { ...event, schema: resolvedEventSchema }\n implementStatement.events[eventName] = { name: newEventName }\n }\n\n // dereference channels\n for (const [channelName, channel] of utils.pairs(this.channels)) {\n const messages: Record<string, { schema: AnyZodObject }> = {}\n for (const [messageName, message] of utils.pairs(channel.messages)) {\n const resolvedMessageSchema = this._dereference(message.schema, entities)\n messages[messageName] = { ...message, schema: resolvedMessageSchema }\n }\n channels[channelName] = { ...channel, messages }\n }\n\n const resolved = {\n actions: actions as ResolvedInterface<TActions, TEvents>['actions'],\n events: events as ResolvedInterface<TActions, TEvents>['events'],\n channels: channels as ResolvedInterface<TActions, TEvents>['channels'],\n }\n\n return {\n resolved,\n implementStatement,\n }\n }\n\n private _dereference(\n generic: GenericZuiSchema<EntityReferences<TEntities>, AnyZodObject>,\n entities: InterfaceResolveInput<TEntities>['entities']\n ): AnyZodObject {\n const entitySchemas: Record<string, AnyZodObject> = {}\n const entityReferences: Record<string, ZodRef> = {}\n for (const [entityName, entity] of utils.pairs(entities)) {\n entitySchemas[entityName] = entity.schema\n entityReferences[entityName] = z.ref(entityName)\n }\n return generic(entityReferences as EntityReferences<TEntities>).dereference(\n entitySchemas as TEntities\n ) as AnyZodObject\n }\n\n private _rename(entities: InterfaceResolveInput<TEntities>['entities'], name: string): string {\n if (!this.templateName) {\n return name\n }\n\n const templateProps = utils.mapValues(entities, (entity) => entity.name) as Record<keyof TEntities, string>\n return this.templateName(name, templateProps)\n }\n}\n", "import { createServer, IncomingMessage, Server } from 'node:http'\nimport { log } from './log'\n\nexport type Request = {\n body?: string\n path: string\n query: string\n method: string\n headers: { [key: string]: string | undefined }\n}\n\nexport type Response = {\n body?: string\n headers?: { [key: string]: string }\n status?: number\n}\n\nexport type Handler = (req: Request) => Promise<Response | void>\n\nexport function parseBody<T>(req: Request): T {\n if (!req.body) {\n throw new Error('Missing body')\n }\n return JSON.parse(req.body)\n}\n\nexport async function serve(\n handler: Handler,\n port: number = 8072,\n callback: (port: number) => void = defaultCallback\n): Promise<Server> {\n /* eslint-disable @typescript-eslint/no-misused-promises */\n const server = createServer(async (req, res) => {\n try {\n const request = await mapIncomingMessageToRequest(req)\n if (request.path === '/health') {\n res.writeHead(200).end('ok')\n return\n }\n const response = await handler(request)\n res.writeHead(response?.status ?? 200, response?.headers ?? {}).end(response?.body ?? '{}')\n } catch (e: any) {\n log.error('Error while handling request', { error: e?.message ?? 'Internal error occured' })\n res.writeHead(500).end(JSON.stringify({ error: e?.message ?? 'Internal error occured' }))\n }\n })\n\n server.listen(port, () => callback(port))\n return server\n}\n\nasync function mapIncomingMessageToRequest(incoming: IncomingMessage): Promise<Request> {\n const body = await readBody(incoming)\n const headers = {} as Request['headers']\n\n for (let i = 0; i < incoming.rawHeaders.length; i += 2) {\n const key = incoming.rawHeaders[i]!.toLowerCase()\n const value = incoming.rawHeaders[i + 1]!\n headers[key] = value\n }\n\n const url = new URL(\n incoming.url ?? '',\n incoming.headers.host ? `http://${incoming.headers.host}` : 'http://botpress.cloud'\n )\n\n return {\n body,\n path: url.pathname,\n query: trimPrefix(url.search, '?'),\n headers,\n method: incoming.method?.toUpperCase() ?? 'GET',\n }\n}\n\nfunction trimPrefix(value: string, prefix: string) {\n return value.indexOf(prefix) === 0 ? value.slice(prefix.length) : value\n}\n\nasync function readBody(incoming: IncomingMessage) {\n return new Promise<string | undefined>((resolve, reject) => {\n if (incoming.method !== 'POST' && incoming.method !== 'PUT' && incoming.method !== 'PATCH') {\n return resolve(undefined)\n }\n\n let body = ''\n\n incoming.on('data', (chunk) => (body += chunk.toString()))\n incoming.on('error', (e) => reject(e))\n incoming.on('end', () => resolve(body))\n })\n}\n\nfunction defaultCallback(port: number) {\n log.info(`Listening on port ${port}`)\n}\n", "export type Logger = {\n debug(message: string, metadata?: any): void\n info(message: string, metadata?: any): void\n warn(message: string, metadata?: any): void\n error(message: string, metadata?: any): void\n}\nexport const log: Logger = console\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { Cast, Merge } from '../type-utils'\nimport { IntegrationSpecificClient } from './client'\nimport { ToTags } from './client/types'\nimport { extractContext, type IntegrationContext } from './context'\nimport { BaseIntegration } from './generic'\nimport { IntegrationLogger, integrationLogger } from './logger'\n\ntype CommonArgs<TIntegration extends BaseIntegration> = {\n ctx: IntegrationContext<TIntegration>\n client: IntegrationSpecificClient<TIntegration>\n logger: IntegrationLogger\n}\n\ntype RegisterPayload = { webhookUrl: string }\ntype RegisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & RegisterPayload\n\ntype UnregisterPayload = { webhookUrl: string }\ntype UnregisterArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & UnregisterPayload\n\ntype WebhookPayload = { req: Request }\ntype WebhookArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & WebhookPayload\n\ntype ActionPayload<T extends string, I> = { type: T; input: I }\ntype ActionArgs<TIntegration extends BaseIntegration, T extends string, I> = CommonArgs<TIntegration> &\n ActionPayload<T, I>\n\ntype CreateUserPayload<TIntegration extends BaseIntegration> = {\n tags: ToTags<keyof TIntegration['user']['tags']>\n}\n\ntype CreateUserArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & CreateUserPayload<TIntegration>\n\ntype CreateConversationPayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'] = keyof TIntegration['channels']\n> = {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n}\n\ntype CreateConversationArgs<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> &\n CreateConversationPayload<TIntegration>\n\ntype MessagePayload<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = {\n type: TMessage\n payload: TIntegration['channels'][TChannel]['messages'][TMessage]\n conversation: Merge<\n Conversation,\n {\n channel: TChannel\n tags: ToTags<keyof TIntegration['channels'][TChannel]['conversation']['tags']>\n }\n >\n message: Merge<\n Message,\n {\n tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']>\n }\n >\n user: Merge<\n User,\n {\n tags: ToTags<keyof TIntegration['user']['tags']>\n }\n >\n}\n\ntype MessageArgs<\n TIntegration extends BaseIntegration,\n TChannel extends keyof TIntegration['channels'],\n TMessage extends keyof TIntegration['channels'][TChannel]['messages']\n> = CommonArgs<TIntegration> &\n MessagePayload<TIntegration, TChannel, TMessage> & {\n ack: (props: { tags: ToTags<keyof TIntegration['channels'][TChannel]['message']['tags']> }) => Promise<void>\n }\n\nexport type RegisterFunction<TIntegration extends BaseIntegration> = (\n props: RegisterArgs<TIntegration>\n) => Promise<void>\n\nexport type UnregisterFunction<TIntegration extends BaseIntegration> = (\n props: UnregisterArgs<TIntegration>\n) => Promise<void>\n\nexport type WebhookFunction<TIntegration extends BaseIntegration> = (\n props: WebhookArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ActionFunctions<TIntegration extends BaseIntegration> = {\n [ActionType in keyof TIntegration['actions']]: (\n props: ActionArgs<TIntegration, Cast<ActionType, string>, TIntegration['actions'][ActionType]['input']>\n ) => Promise<TIntegration['actions'][ActionType]['output']>\n}\n\nexport type CreateUserFunction<TIntegration extends BaseIntegration> = (\n props: CreateUserArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type CreateConversationFunction<TIntegration extends BaseIntegration> = (\n props: CreateConversationArgs<TIntegration>\n) => Promise<Response | void>\n\nexport type ChannelFunctions<TIntegration extends BaseIntegration> = {\n [ChannelName in keyof TIntegration['channels']]: {\n messages: {\n [MessageType in keyof TIntegration['channels'][ChannelName]['messages']]: (\n props: CommonArgs<TIntegration> & MessageArgs<TIntegration, ChannelName, MessageType>\n ) => Promise<void>\n }\n }\n}\n\nexport type IntegrationHandlers<TIntegration extends BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n webhook: WebhookFunction<TIntegration>\n createUser?: CreateUserFunction<TIntegration>\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\ntype ServerProps<TIntegration extends BaseIntegration> = CommonArgs<TIntegration> & {\n req: Request\n instance: IntegrationHandlers<TIntegration>\n}\n\nexport const integrationHandler =\n <TIntegration extends BaseIntegration>(instance: IntegrationHandlers<TIntegration>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext<TIntegration>(req.headers)\n\n const vanillaClient = new Client({\n botId: ctx.botId,\n integrationId: ctx.integrationId,\n retry: retryConfig,\n })\n const client = new IntegrationSpecificClient<TIntegration>(vanillaClient)\n\n const props = {\n ctx,\n req,\n client,\n logger: integrationLogger,\n instance,\n }\n\n try {\n let response: Response | void\n switch (ctx.operation) {\n case 'webhook_received':\n response = await onWebhook<TIntegration>(props)\n break\n case 'register':\n response = await onRegister<TIntegration>(props)\n break\n case 'unregister':\n response = await onUnregister<TIntegration>(props)\n break\n case 'message_created':\n response = await onMessageCreated<TIntegration>(props)\n break\n case 'action_triggered':\n response = await onActionTriggered<TIntegration>(props)\n break\n case 'ping':\n response = await onPing<TIntegration>(props)\n break\n case 'create_user':\n response = await onCreateUser<TIntegration>(props)\n break\n case 'create_conversation':\n response = await onCreateConversation<TIntegration>(props)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n return response ? { ...response, status: response.status ?? 200 } : { status: 200 }\n } catch (thrown) {\n if (isApiError(thrown)) {\n const runtimeError = new RuntimeError(thrown.message, thrown)\n integrationLogger.forBot().error(runtimeError.message)\n\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n\n // prints the error in the integration logs\n console.error(thrown)\n\n const runtimeError = new RuntimeError(\n 'An unexpected error occurred in the integration. Bot owners: Check logs for more informations. Integration owners: throw a RuntimeError to return a custom error message instead.'\n )\n integrationLogger.forBot().error(runtimeError.message)\n return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n }\n\nconst onPing = async <TIntegration extends BaseIntegration>(_: ServerProps<TIntegration>) => {}\n\nconst onWebhook = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req: incomingRequest,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { req } = parseBody<WebhookPayload>(incomingRequest)\n return instance.webhook({ client, ctx, req, logger })\n}\n\nconst onRegister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.register) {\n return\n }\n const { webhookUrl } = parseBody<RegisterPayload>(req)\n await instance.register({ client, ctx, webhookUrl, logger })\n}\n\nconst onUnregister = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.unregister) {\n return\n }\n const { webhookUrl } = parseBody<UnregisterPayload>(req)\n await instance.unregister({ ctx, webhookUrl, client, logger })\n}\n\nconst onCreateUser = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createUser) {\n return\n }\n const { tags } = parseBody<CreateUserPayload<TIntegration>>(req)\n return await instance.createUser({ ctx, client, tags, logger })\n}\n\nconst onCreateConversation = async <TIntegration extends BaseIntegration>({\n client,\n ctx,\n req,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n if (!instance.createConversation) {\n return\n }\n const { channel, tags } = parseBody<CreateConversationPayload<TIntegration>>(req)\n return await instance.createConversation({ ctx, client, channel, tags, logger })\n}\n\nconst onMessageCreated = async <TIntegration extends BaseIntegration>({\n ctx,\n req,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { conversation, user, type, payload, message } = parseBody<MessagePayload<TIntegration, string, string>>(req)\n\n const channelHandler = instance.channels[conversation.channel]\n\n if (!channelHandler) {\n throw new Error(`Channel ${conversation.channel} not found`)\n }\n\n const messageHandler = channelHandler.messages[type]\n\n if (!messageHandler) {\n throw new Error(`Message of type ${type} not found in channel ${conversation.channel}`)\n }\n\n type UpdateMessageProps = Parameters<(typeof client)['updateMessage']>[0]\n const ack = async ({ tags }: Pick<UpdateMessageProps, 'tags'>) => {\n await client.updateMessage({\n id: message.id,\n tags,\n })\n }\n\n await messageHandler({ ctx, conversation, message, user, type, client, payload, ack, logger })\n}\n\nconst onActionTriggered = async <TIntegration extends BaseIntegration>({\n req,\n ctx,\n client,\n logger,\n instance,\n}: ServerProps<TIntegration>) => {\n const { input, type } = parseBody<ActionPayload<string, any>>(req)\n\n if (!type) {\n throw new Error('Missing action type')\n }\n\n const action = instance.actions[type]\n\n if (!action) {\n throw new Error(`Action ${type} not found`)\n }\n\n const output = await action({ ctx, input, client, type, logger })\n\n return {\n body: JSON.stringify({ output }),\n }\n}\n", "import { RetryConfig, axiosRetry } from '@botpress/client'\n\nexport const retryConfig: RetryConfig = {\n retries: 3,\n retryCondition: (err) =>\n axiosRetry.isNetworkOrIdempotentRequestError(err) || [429, 502].includes(err.response?.status ?? 0),\n retryDelay: (retryCount) => retryCount * 1000,\n}\n", "import { Client } from '@botpress/client'\nimport { BaseIntegration } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the integration's properties.\n */\nexport class IntegrationSpecificClient<TIntegration extends BaseIntegration> {\n public constructor(private readonly _client: Client) {}\n\n public createConversation: routes.CreateConversation<TIntegration> = ((x) =>\n this._client.createConversation(x)) as routes.CreateConversation<TIntegration>\n public getConversation: routes.GetConversation<TIntegration> = ((x) =>\n this._client.getConversation(x)) as routes.GetConversation<TIntegration>\n public listConversations: routes.ListConversations<TIntegration> = ((x) =>\n this._client.listConversations(x)) as routes.ListConversations<TIntegration>\n public getOrCreateConversation: routes.GetOrCreateConversation<TIntegration> = ((x) =>\n this._client.getOrCreateConversation(x)) as routes.GetOrCreateConversation<TIntegration>\n public updateConversation: routes.UpdateConversation<TIntegration> = ((x) =>\n this._client.updateConversation(x)) as routes.UpdateConversation<TIntegration>\n public deleteConversation: routes.DeleteConversation<TIntegration> = ((x) =>\n this._client.deleteConversation(x)) as routes.DeleteConversation<TIntegration>\n\n public listParticipants: routes.ListParticipants<TIntegration> = ((x) =>\n this._client.listParticipants(x)) as routes.ListParticipants<TIntegration>\n public addParticipant: routes.AddParticipant<TIntegration> = ((x) =>\n this._client.addParticipant(x)) as routes.AddParticipant<TIntegration>\n public getParticipant: routes.GetParticipant<TIntegration> = ((x) =>\n this._client.getParticipant(x)) as routes.GetParticipant<TIntegration>\n public removeParticipant: routes.RemoveParticipant<TIntegration> = ((x) =>\n this._client.removeParticipant(x)) as routes.RemoveParticipant<TIntegration>\n\n public createEvent: routes.CreateEvent<TIntegration> = ((x) =>\n this._client.createEvent(x)) as routes.CreateEvent<TIntegration>\n public getEvent: routes.GetEvent<TIntegration> = ((x) => this._client.getEvent(x)) as routes.GetEvent<TIntegration>\n public listEvents: routes.ListEvents<TIntegration> = ((x) =>\n this._client.listEvents(x)) as routes.ListEvents<TIntegration>\n\n public createMessage: routes.CreateMessage<TIntegration> = ((x) =>\n this._client.createMessage(x)) as routes.CreateMessage<TIntegration>\n public getOrCreateMessage: routes.GetOrCreateMessage<TIntegration> = ((x) =>\n this._client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TIntegration>\n public getMessage: routes.GetMessage<TIntegration> = ((x) =>\n this._client.getMessage(x)) as routes.GetMessage<TIntegration>\n public updateMessage: routes.UpdateMessage<TIntegration> = ((x) =>\n this._client.updateMessage(x)) as routes.UpdateMessage<TIntegration>\n public listMessages: routes.ListMessages<TIntegration> = ((x) =>\n this._client.listMessages(x)) as routes.ListMessages<TIntegration>\n public deleteMessage: routes.DeleteMessage<TIntegration> = ((x) =>\n this._client.deleteMessage(x)) as routes.DeleteMessage<TIntegration>\n\n public createUser: routes.CreateUser<TIntegration> = ((x) =>\n this._client.createUser(x)) as routes.CreateUser<TIntegration>\n public getUser: routes.GetUser<TIntegration> = ((x) => this._client.getUser(x)) as routes.GetUser<TIntegration>\n public listUsers: routes.ListUsers<TIntegration> = (x) => this._client.listUsers(x)\n public getOrCreateUser: routes.GetOrCreateUser<TIntegration> = ((x) =>\n this._client.getOrCreateUser(x)) as routes.GetOrCreateUser<TIntegration>\n public updateUser: routes.UpdateUser<TIntegration> = ((x) =>\n this._client.updateUser(x)) as routes.UpdateUser<TIntegration>\n public deleteUser: routes.DeleteUser<TIntegration> = (x) => this._client.deleteUser(x)\n\n public getState: routes.GetState<TIntegration> = ((x) => this._client.getState(x)) as routes.GetState<TIntegration>\n public setState: routes.SetState<TIntegration> = ((x) => this._client.setState(x)) as routes.SetState<TIntegration>\n public getOrSetState: routes.GetOrSetState<TIntegration> = ((x) =>\n this._client.getOrSetState(x)) as routes.GetOrSetState<TIntegration>\n public patchState: routes.PatchState<TIntegration> = ((x) =>\n this._client.patchState(x)) as routes.PatchState<TIntegration>\n\n public configureIntegration: routes.ConfigureIntegration<TIntegration> = (x) => this._client.configureIntegration(x)\n\n public uploadFile: routes.UploadFile<TIntegration> = (x) => this._client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TIntegration> = (x) => this._client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TIntegration> = (x) => this._client.deleteFile(x)\n public listFiles: routes.ListFiles<TIntegration> = (x) => this._client.listFiles(x)\n public getFile: routes.GetFile<TIntegration> = (x) => this._client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TIntegration> = (x) => this._client.updateFileMetadata(x)\n}\n", "import util from 'util'\n\nconst serializeForBotMessage = (args: Parameters<typeof util.format>) => {\n if (process.env['BP_LOG_FORMAT'] === 'json') {\n return JSON.stringify({ msg: util.format(...args), visible_to_bot_owner: true })\n } else {\n const [format, ...param] = args\n return util.format(`[For Bot Owner] ${format}`, ...param)\n }\n}\n\nexport const integrationLogger = {\n /**\n * Use this function to log messages that will be displayed to the Bot Owner.\n */\n forBot: () => {\n return {\n info: (...args: Parameters<typeof console.info>) => {\n console.info(serializeForBotMessage(args))\n },\n warn: (...args: Parameters<typeof console.warn>) => {\n console.warn(serializeForBotMessage(args))\n },\n error: (...args: Parameters<typeof console.error>) => {\n console.error(serializeForBotMessage(args))\n },\n debug: (...args: Parameters<typeof console.debug>) => {\n console.debug(serializeForBotMessage(args))\n },\n }\n },\n}\n\nexport type IntegrationLogger = typeof integrationLogger\n", "import type { Server } from 'node:http'\nimport { serve } from '../serve'\nimport { BaseIntegration } from './generic'\nimport {\n RegisterFunction,\n UnregisterFunction,\n WebhookFunction,\n CreateUserFunction,\n CreateConversationFunction,\n ActionFunctions,\n ChannelFunctions,\n integrationHandler,\n} from './server'\n\nexport type IntegrationImplementationProps<TIntegration extends BaseIntegration = BaseIntegration> = {\n register: RegisterFunction<TIntegration>\n unregister: UnregisterFunction<TIntegration>\n handler: WebhookFunction<TIntegration>\n /**\n * @deprecated\n */\n createUser?: CreateUserFunction<TIntegration>\n /**\n * @deprecated\n */\n createConversation?: CreateConversationFunction<TIntegration>\n actions: ActionFunctions<TIntegration>\n channels: ChannelFunctions<TIntegration>\n}\n\nexport class IntegrationImplementation<TIntegration extends BaseIntegration = BaseIntegration> {\n public readonly props: IntegrationImplementationProps<TIntegration>\n public readonly actions: IntegrationImplementationProps<TIntegration>['actions']\n public readonly channels: IntegrationImplementationProps<TIntegration>['channels']\n public readonly register: IntegrationImplementationProps<TIntegration>['register']\n public readonly unregister: IntegrationImplementationProps<TIntegration>['unregister']\n public readonly createUser: IntegrationImplementationProps<TIntegration>['createUser']\n public readonly createConversation: IntegrationImplementationProps<TIntegration>['createConversation']\n public readonly webhook: IntegrationImplementationProps<TIntegration>['handler']\n\n public constructor(props: IntegrationImplementationProps<TIntegration>) {\n this.props = props\n this.actions = props.actions\n this.channels = props.channels\n this.register = props.register\n this.unregister = props.unregister\n this.createUser = props.createUser\n this.createConversation = props.createConversation\n this.webhook = props.handler\n }\n\n public readonly handler = integrationHandler<TIntegration>(this)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n", "import { InterfaceDeclaration } from '../integration'\nimport * as messages from '../message'\nimport z, { AnyZodObject } from '../zui'\n\nconst withUserId = <S extends z.AnyZodObject>(s: { schema: S }) => ({\n ...s,\n schema: () =>\n s.schema.extend({\n userId: z.string().optional().describe('Allows sending a message pretending to be a certain user'),\n }),\n})\n\nconst messageSourceSchema = z.union([\n z.object({ type: z.literal('user'), userId: z.string() }),\n z.object({ type: z.literal('bot') }),\n])\n\ntype Tuple<T> = [T, T, ...T[]]\nconst messagePayloadSchemas: AnyZodObject[] = Object.entries(messages.defaults).map(([k, v]) =>\n z.object({\n source: messageSourceSchema,\n type: z.literal(k),\n payload: v.schema,\n })\n)\n\nconst messageSchema = z.union(messagePayloadSchemas as Tuple<AnyZodObject>)\n\nexport const hitl = new InterfaceDeclaration({\n name: 'hitl',\n version: '0.4.0',\n entities: {},\n events: {\n hitlAssigned: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n userId: z.string(),\n }),\n },\n hitlStopped: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n }),\n },\n },\n actions: {\n createUser: {\n input: {\n schema: () =>\n z.object({\n name: z.string().optional(),\n pictureUrl: z.string().optional(),\n email: z.string().optional(),\n }),\n },\n output: {\n schema: () =>\n z.object({\n userId: z.string(),\n }),\n },\n },\n startHitl: {\n input: {\n schema: () =>\n z.object({\n userId: z.string(),\n title: z.string(),\n description: z.string().optional(),\n messageHistory: z\n .array(messageSchema)\n .optional()\n .describe('Message history to display in the HITL session'),\n }),\n },\n output: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n }),\n },\n },\n stopHitl: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n reason: z.enum(['timeout', 'cancel']).optional(),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n channels: {\n hitl: {\n messages: {\n text: withUserId(messages.defaults.text),\n },\n },\n },\n})\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst ToolCallSchema = z.object({\n id: z.string(),\n type: z.enum(['function']),\n function: z.object({\n name: z.string(),\n arguments: z\n .record(z.any())\n .nullable()\n .describe('Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.'),\n }),\n})\n\nconst ToolChoiceSchema = z.object({\n // TODO: remove empty value from enum once Studio issue is fixed\n type: z.enum(['auto', 'specific', 'any', 'none', '']).optional(), // note: Claude doesn't support \"none\" but we can simply strip out the tools when `type` is \"none\"\n functionName: z.string().optional().describe('Required if `type` is \"specific\"'),\n})\n\nconst MessageSchema = z.object({\n role: z.enum(['user', 'assistant']),\n type: z.enum(['text', 'tool_calls', 'tool_result', 'multipart']).default('text'),\n toolCalls: z.array(ToolCallSchema).optional().describe('Required if `type` is \"tool_calls\"'),\n toolResultCallId: z.string().optional().describe('Required if `type` is \"tool_result\"'), // note: not supported by Gemini\n content: z\n .string()\n // TODO: union types are not supported yet by the Studio, comment this out when testing via an action card in the Studio\n .or(\n z.array(\n z.object({\n type: z.enum(['text', 'image']),\n mimeType: z\n .string()\n .optional()\n .describe(\n 'Indicates the MIME type of the content. If not provided it will be detected from the content-type header of the provided URL.'\n ),\n text: z.string().optional().describe('Required if part type is \"text\" '),\n url: z.string().optional().describe('Required if part type is \"image\"'),\n })\n )\n )\n .optional()\n .nullable()\n .describe(\n 'Required unless `type` is \"tool_call\". If `type` is \"multipart\", this field must be an array of content objects. If `type` is \"tool_result\" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is \"tool_call\" then the `toolCalls` field should be used instead.'\n ),\n})\n\nconst ModelRefSchema = z.object({ id: z.string() })\n\nconst ModelSchema = ModelRefSchema.extend({\n name: z.string(),\n description: z.string(),\n tags: z.array(\n z.enum([\n 'recommended',\n 'deprecated',\n 'general-purpose',\n 'low-cost',\n 'vision',\n 'coding',\n 'agents',\n 'function-calling',\n 'roleplay',\n 'storytelling',\n ])\n ),\n input: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n output: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n})\n\nconst GenerateContentInputSchema = <S extends z.ZodSchema>(modelRefSchema: S) =>\n z.object({\n model: modelRefSchema.describe('Model to use for content generation').optional(),\n systemPrompt: z.string().optional().describe('Optional system prompt to guide the model'),\n messages: z.array(MessageSchema).describe('Array of messages for the model to process'),\n responseFormat: z\n .enum(['text', 'json_object'])\n .optional()\n .describe(\n 'Response format expected from the model. If \"json_object\" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'\n ), // note: only OpenAI and Groq support this but for other models we can just append this as an indication in the system prompt\n // note: we don't support streaming yet\n maxTokens: z.number().optional().describe('Maximum number of tokens allowed in the generated response'),\n temperature: z\n .number()\n .min(0)\n .max(2)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .default(1)\n .describe('Sampling temperature for the model. Higher values result in more random outputs.'),\n topP: z\n .number()\n .min(0)\n .max(1)\n .default(1)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .describe(\n 'Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold.'\n ), // TODO: .placeholder() from zui doesn't work, so we have to use .default() which introduces some typing issues\n // note: topK is supported by Claude and Gemini but not by OpenAI or Groq\n stopSequences: z\n .array(z.string())\n .max(4)\n .optional()\n .describe('Sequences where the model should stop generating further tokens.'),\n tools: z\n .array(\n z.object({\n type: z.literal('function'),\n function: z.object({\n name: z.string().describe('Function name'),\n description: z.string().optional(),\n argumentsSchema: z.object({}).passthrough().optional().describe('JSON schema of the function arguments'),\n }),\n })\n )\n .optional(),\n // TODO: an object with options doesn't seem to be supported by the Studio as it's not rendering correctly, the dropdown for \"type\" is not working and it's sending a blank value instead which causes a schema validation error unless an empty value is allowed in the `type` enum\n toolChoice: ToolChoiceSchema.optional(), // note: Gemini doesn't support this but we can just ignore it there\n userId: z.string().optional(),\n debug: z.boolean().optional().hidden().describe('Set to `true` to output debug information to the bot logs'),\n meta: z\n .object({\n promptCategory: z\n .string()\n .optional()\n .describe('Category of the prompt, e.g. cards/ai-generate, cards/ai-task, nodes/autonomous, etc.'),\n integrationName: z\n .string()\n .optional()\n .describe('Name of the integration that originally received the message that initiated this action'),\n })\n .optional()\n .hidden(),\n })\n\nconst GenerateContentInputBaseSchema = GenerateContentInputSchema(ModelRefSchema)\n\nconst GenerateContentOutputSchema = z.object({\n id: z.string().describe('Response ID from LLM provider'),\n provider: z.string().describe('LLM provider name'),\n model: z.string().describe('Model name'),\n choices: z.array(\n MessageSchema.omit({ role: true }).extend({\n role: z.literal('assistant'),\n index: z.number().int(),\n stopReason: z.enum(['stop', 'max_tokens', 'tool_calls', 'content_filter', 'other']),\n // note: stopSequence is supported by Claude but not by OpenAI, Groq or Gemini\n })\n ),\n usage: z.object({\n inputTokens: z.number().int().describe('Number of input tokens used by the model'),\n inputCost: z.number().describe('Cost of the input tokens received by the model, in U.S. dollars'),\n outputTokens: z.number().int().describe('Number of output tokens used by the model'),\n outputCost: z.number().describe('Cost of the output tokens generated by the model, in U.S. dollars'),\n }),\n botpress: z.object({\n cost: z.number().describe('Total cost of the content generation, in U.S. dollars'),\n }),\n})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '5.1.0',\n entities: {\n modelRef: {\n schema: ModelRefSchema,\n },\n },\n events: {},\n actions: {\n generateContent: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ modelRef }) => GenerateContentInputSchema(modelRef),\n },\n output: {\n schema: () => GenerateContentOutputSchema,\n },\n },\n listLanguageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ modelRef }) =>\n z.object({\n models: z.array(z.intersection(ModelSchema, modelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace llm {\n export type GenerateContentInput = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateContentOutput = z.infer<typeof GenerateContentOutputSchema>\n export type ToolCall = z.infer<typeof ToolCallSchema>\n export type Message = z.infer<typeof MessageSchema>\n export type Model = z.infer<typeof ModelSchema>\n export type ModelDetails = Omit<Model, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\nimport { OpenAITranscribeAudioOutputSchema } from './schemas/speech-to-text'\n\nconst SpeechModelRefSchema = z.object({\n id: z.string(),\n})\n\nconst SpeechToTextModelSchema = SpeechModelRefSchema.extend({\n name: z.string(),\n costPerMinute: z.number().describe('Cost per minute of speech transcription, in U.S. dollars'),\n})\n\nconst TranscribeAudioInputSchema = <TModelRef extends z.ZodSchema>(imageModelRefSchema: TModelRef) =>\n z.object({\n model: imageModelRefSchema.optional().describe('Model to use for speech-to-text transcription (optional)'),\n fileUrl: z\n .string()\n .url()\n .describe(\n 'URL of the audio file to transcribe. The URL should return a content-type header in order to detect the audio format. Supported audio formats supported are: mp3, mp4, mpeg, mpga, m4a, wav, webm'\n ),\n language: z\n .string()\n .optional()\n .describe(\n 'The language of the input audio (optional). Supplying the input language in ISO-639-1 format will improve accuracy and latency.'\n ),\n prompt: z\n .string()\n .optional()\n .describe(\n \"An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.\"\n ),\n temperature: z\n .number()\n .default(0)\n .optional()\n .describe(\n 'The sampling temperature (optional), between 0 and 1. Defaults to 0 (automatic). Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.'\n ),\n })\n\nconst TranscribeAudioBaseSchema = TranscribeAudioInputSchema(SpeechModelRefSchema)\n\nconst TranscribeAudioOutputSchema = OpenAITranscribeAudioOutputSchema.extend({\n model: z.string().describe('Model name used'),\n cost: z.number().describe('Total cost of the transcription, in U.S. dollars (DEPRECATED)'),\n botpress: z.object({\n cost: z.number().describe('Total cost of the transcription, in U.S. dollars'),\n }),\n})\n\nexport const speechToText = new InterfaceDeclaration({\n name: 'speechToText',\n version: '2.0.0',\n entities: {\n speechToTextModelRef: {\n schema: SpeechModelRefSchema,\n },\n },\n actions: {\n transcribeAudio: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ speechToTextModelRef }) => TranscribeAudioInputSchema(speechToTextModelRef),\n },\n output: {\n schema: () => TranscribeAudioOutputSchema,\n },\n },\n listSpeechToTextModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ speechToTextModelRef }) =>\n z.object({\n models: z.array(z.intersection(SpeechToTextModelSchema, speechToTextModelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace speechToText {\n export type TranscribeAudioInputSchema = z.infer<typeof TranscribeAudioBaseSchema>\n export type TranscribeAudioOutputSchema = z.infer<typeof TranscribeAudioOutputSchema>\n export type SpeechToTextModel = z.infer<typeof SpeechToTextModelSchema>\n export type SpeechToTextModelDetails = Omit<SpeechToTextModel, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst baseItem = z.object({ id: z.string() })\nconst withId = (schema: z.ZodTypeAny) => z.intersection(schema, baseItem)\n\nconst capitalize = (s: string) => s[0]!.toUpperCase() + s.slice(1)\nconst camelCase = (...parts: string[]) => {\n const [first, ...rest] = parts.filter((s) => s.length > 0).map((s) => s.toLowerCase())\n if (!first) {\n return ''\n }\n return [first, ...rest.map(capitalize)].join('')\n}\n\nconst nextToken = z.string().optional()\nexport const listable = new InterfaceDeclaration({\n name: 'listable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n list: {\n input: {\n schema: () => z.object({ nextToken }),\n },\n output: {\n schema: (args) =>\n z.object({\n items: z.array(withId(args.item)),\n meta: z.object({ nextToken }),\n }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueList\n})\n\nexport const creatable = new InterfaceDeclaration({\n name: 'creatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n created: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n create: {\n input: {\n schema: (args) => z.object({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueCreate, issueCreated\n})\n\nexport const readable = new InterfaceDeclaration({\n name: 'readable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {},\n actions: {\n read: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueRead\n})\n\nexport const updatable = new InterfaceDeclaration({\n name: 'updatable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n updated: {\n schema: (args) =>\n z.object({\n item: withId(args.item),\n }),\n },\n },\n actions: {\n update: {\n input: {\n schema: (args) => baseItem.extend({ item: args.item }),\n },\n output: {\n schema: (args) => z.object({ item: withId(args.item) }),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueUpdate, issueUpdated\n})\n\nexport const deletable = new InterfaceDeclaration({\n name: 'deletable',\n version: '0.0.1',\n entities: {\n item: {\n schema: baseItem,\n },\n },\n events: {\n deleted: {\n schema: () => baseItem,\n },\n },\n actions: {\n delete: {\n input: {\n schema: () => baseItem,\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n templateName: (name, props) => camelCase(props.item, name), // issueDelete, issueDeleted\n})\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst ImageModelRefSchema = z.object({\n id: z.string(),\n})\n\nconst ImageModelSchema = ImageModelRefSchema.extend({\n name: z.string(),\n costPerImage: z.number().describe('Cost per image generation, in U.S. dollars'),\n sizes: z.array(z.string()).describe('Available image sizes'),\n defaultSize: z.string().describe('Default image size generated by model'),\n})\n\nconst ImageGenerationParamsSchema = z.object({}).describe('Model-specific parameters for image generation')\n\nconst GenerateImageInputSchema = <TModelRef extends z.ZodSchema, TParams extends z.ZodSchema>(\n imageModelRefSchema: TModelRef,\n paramsSchema: TParams\n) =>\n z.object({\n model: imageModelRefSchema.optional().describe('Model to use for image generation'),\n prompt: z.string(),\n size: z.string().optional(),\n expiration: z\n .number()\n .int()\n .min(30)\n .max(90)\n .optional()\n .describe(\n 'Expiration of the generated image in days, after which the image will be automatically deleted to free up storage space in your account. The default is to keep the image indefinitely (no expiration). The minimum is 30 days and the maximum is 90 days.'\n ),\n params: paramsSchema.optional(),\n })\n\nconst GenerateContentInputBaseSchema = GenerateImageInputSchema(ImageModelRefSchema, ImageGenerationParamsSchema)\n\nconst GenerateImageOutputSchema = z.object({\n model: z.string().describe('Model name used'),\n imageUrl: z.string().describe('Temporary URL of generated image'),\n cost: z.number().describe('Cost of the image generation, in U.S. dollars (DEPRECATED)'),\n botpress: z.object({\n cost: z.number().describe('Cost of the image generation, in U.S. dollars'),\n }),\n})\n\nexport const textToImage = new InterfaceDeclaration({\n name: 'textToImage',\n version: '2.1.0',\n entities: {\n imageModelRef: {\n schema: ImageModelRefSchema,\n },\n imageGenerationParams: {\n schema: ImageGenerationParamsSchema,\n },\n },\n actions: {\n generateImage: {\n billable: true,\n cacheable: true,\n input: {\n schema: ({ imageModelRef, imageGenerationParams }) =>\n GenerateImageInputSchema(imageModelRef, imageGenerationParams),\n },\n output: {\n schema: () => GenerateImageOutputSchema,\n },\n },\n listImageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ imageModelRef }) =>\n z.object({\n models: z.array(z.intersection(ImageModelSchema, imageModelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace textToImage {\n export type GenerateImageInputSchema = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateImageOutputSchema = z.infer<typeof GenerateImageOutputSchema>\n export type ImageModel = z.infer<typeof ImageModelSchema>\n export type ImageModelDetails = Omit<ImageModel, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration'\nimport z from '../zui'\n\nexport const typingIndicator = new InterfaceDeclaration({\n name: 'typingIndicator',\n version: '0.0.1',\n entities: {},\n events: {},\n actions: {\n startTypingIndicator: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n messageId: z.string().describe('The message ID to which the typing indicator should be attached'),\n timeout: z\n .number()\n .optional()\n .describe('The timeout in milliseconds after which the typing indicator should stop'),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n stopTypingIndicator: {\n input: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n messageId: z.string().describe('The message ID from which the typing indicator should be removed'),\n }),\n },\n output: {\n schema: () => z.object({}),\n },\n },\n },\n})\n", "import * as client from '@botpress/client'\nimport { log } from '../log'\nimport { retryConfig } from '../retry'\nimport { Request, Response, parseBody } from '../serve'\nimport { BotSpecificClient } from './client'\nimport * as types from './client/types'\nimport { BotContext, extractContext } from './context'\nimport { BaseBot } from './generic'\n\ntype CommonArgs<TBot extends BaseBot> = {\n ctx: BotContext\n client: BotSpecificClient<TBot>\n}\n\ntype MessagePayload<TBot extends BaseBot> = {\n user: client.User\n conversation: client.Conversation\n message: types.MessageResponse<TBot>['message']\n event: client.Event\n states: {\n [TState in keyof TBot['states']]: {\n type: StateType\n payload: TBot['states'][TState]\n }\n }\n}\ntype MessageArgs<TBot extends BaseBot> = CommonArgs<TBot> & MessagePayload<TBot>\n\ntype EventPayload<TBot extends BaseBot> = types.EventResponse<TBot>\ntype EventArgs<TBot extends BaseBot> = CommonArgs<TBot> & EventPayload<TBot>\n\ntype StateExpiredPayload = { state: client.State }\ntype StateExpiredArgs<TBot extends BaseBot> = CommonArgs<TBot> & StateExpiredPayload\n\nexport type StateType = 'conversation' | 'user' | 'bot'\n\nexport type MessageHandler<TBot extends BaseBot> = (args: MessageArgs<TBot>) => Promise<void>\n\nexport type EventHandler<TBot extends BaseBot> = (args: EventArgs<TBot>) => Promise<void>\n\nexport type StateExpiredHandler<TBot extends BaseBot> = (args: StateExpiredArgs<TBot>) => Promise<void>\n\nexport type BotHandlers<TBot extends BaseBot> = {\n messageHandlers: MessageHandler<TBot>[]\n eventHandlers: EventHandler<TBot>[]\n stateExpiredHandlers: StateExpiredHandler<TBot>[]\n}\n\ntype ServerProps<TBot extends BaseBot> = CommonArgs<TBot> & {\n req: Request\n instance: BotHandlers<TBot>\n}\n\nexport const botHandler =\n <TBot extends BaseBot>(instance: BotHandlers<TBot>) =>\n async (req: Request): Promise<Response | void> => {\n const ctx = extractContext(req.headers)\n\n if (ctx.operation !== 'ping') {\n log.info(`Received ${ctx.operation} operation for bot ${ctx.botId} of type ${ctx.type}`)\n }\n\n const vanillaClient = new client.Client({\n botId: ctx.botId,\n retry: retryConfig,\n })\n const botClient = new BotSpecificClient<TBot>(vanillaClient)\n\n const props: ServerProps<TBot> = {\n req,\n ctx,\n client: botClient,\n instance,\n }\n\n switch (ctx.operation) {\n case 'action_triggered':\n throw new Error(`Operation ${ctx.operation} not supported yet`)\n case 'event_received':\n await onEventReceived<TBot>(props as ServerProps<TBot>)\n break\n case 'register':\n await onRegister<TBot>(props as ServerProps<TBot>)\n break\n case 'unregister':\n await onUnregister<TBot>(props as ServerProps<TBot>)\n break\n case 'ping':\n await onPing<TBot>(props as ServerProps<TBot>)\n break\n default:\n throw new Error(`Unknown operation ${ctx.operation}`)\n }\n\n return { status: 200 }\n }\n\nconst onPing = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onRegister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onUnregister = async <TBot extends BaseBot>(_: ServerProps<TBot>) => {}\nconst onEventReceived = async <TBot extends BaseBot>({ ctx, req, client, instance }: ServerProps<TBot>) => {\n log.debug(`Received event ${ctx.type}`)\n\n const body = parseBody<EventPayload<TBot>>(req)\n const event = body.event as client.Event\n\n switch (ctx.type) {\n case 'message_created':\n const messagePayload: MessagePayload<TBot> = {\n user: event.payload.user,\n conversation: event.payload.conversation,\n message: event.payload.message,\n states: event.payload.states,\n event,\n }\n\n await Promise.all(\n instance.messageHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...messagePayload,\n })\n )\n )\n break\n case 'state_expired':\n const statePayload: StateExpiredPayload = { state: event.payload.state }\n await Promise.all(\n instance.stateExpiredHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...statePayload,\n })\n )\n )\n break\n default:\n const eventPayload = { event: body.event } as EventPayload<TBot>\n await Promise.all(\n instance.eventHandlers.map((handler) =>\n handler({\n client,\n ctx,\n ...eventPayload,\n })\n )\n )\n }\n}\n", "import { Client } from '@botpress/client'\nimport { BaseBot } from '../generic'\nimport * as routes from './routes'\n\n/**\n * Just like the regular botpress client, but typed with the bot's properties.\n */\nexport class BotSpecificClient<TBot extends BaseBot> {\n public constructor(private readonly _client: Client) {}\n\n public getConversation: routes.GetConversation<TBot> = (x) => this._client.getConversation(x)\n public listConversations: routes.ListConversations<TBot> = (x) => this._client.listConversations(x)\n public updateConversation: routes.UpdateConversation<TBot> = (x) => this._client.updateConversation(x)\n public deleteConversation: routes.DeleteConversation<TBot> = (x) => this._client.deleteConversation(x)\n\n public listParticipants: routes.ListParticipants<TBot> = (x) => this._client.listParticipants(x)\n public addParticipant: routes.AddParticipant<TBot> = (x) => this._client.addParticipant(x)\n public getParticipant: routes.GetParticipant<TBot> = (x) => this._client.getParticipant(x)\n public removeParticipant: routes.RemoveParticipant<TBot> = (x) => this._client.removeParticipant(x)\n\n public getEvent: routes.GetEvent<TBot> = ((x) => this._client.getEvent(x)) as routes.GetEvent<TBot>\n public listEvents: routes.ListEvents<TBot> = ((x) => this._client.listEvents(x)) as routes.ListEvents<TBot>\n\n public createMessage: routes.CreateMessage<TBot> = ((x) =>\n this._client.createMessage(x)) as routes.CreateMessage<TBot>\n public getOrCreateMessage: routes.GetOrCreateMessage<TBot> = ((x) =>\n this._client.getOrCreateMessage(x)) as routes.GetOrCreateMessage<TBot>\n public getMessage: routes.GetMessage<TBot> = ((x) => this._client.getMessage(x)) as routes.GetMessage<TBot>\n public updateMessage: routes.UpdateMessage<TBot> = ((x) =>\n this._client.updateMessage(x)) as routes.UpdateMessage<TBot>\n public listMessages: routes.ListMessages<TBot> = ((x) => this._client.listMessages(x)) as routes.ListMessages<TBot>\n public deleteMessage: routes.DeleteMessage<TBot> = ((x) =>\n this._client.deleteMessage(x)) as routes.DeleteMessage<TBot>\n\n public getUser: routes.GetUser<TBot> = (x) => this._client.getUser(x)\n public listUsers: routes.ListUsers<TBot> = (x) => this._client.listUsers(x)\n public updateUser: routes.UpdateUser<TBot> = (x) => this._client.updateUser(x)\n public deleteUser: routes.DeleteUser<TBot> = (x) => this._client.deleteUser(x)\n\n public getState: routes.GetState<TBot> = ((x) =>\n this._client\n .getState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this._client\n .setState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.SetState<TBot>\n public getOrSetState: routes.GetOrSetState<TBot> = ((x) =>\n this._client\n .getOrSetState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetOrSetState<TBot>\n public patchState: routes.PatchState<TBot> = ((x) =>\n this._client\n .patchState(x)\n .then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.PatchState<TBot>\n\n public callAction: routes.CallAction<TBot> = (x) => this._client.callAction(x)\n\n public uploadFile: routes.UploadFile<TBot> = (x) => this._client.uploadFile(x)\n public upsertFile: routes.UpsertFile<TBot> = (x) => this._client.upsertFile(x)\n public deleteFile: routes.DeleteFile<TBot> = (x) => this._client.deleteFile(x)\n public listFiles: routes.ListFiles<TBot> = (x) => this._client.listFiles(x)\n public getFile: routes.GetFile<TBot> = (x) => this._client.getFile(x)\n public updateFileMetadata: routes.UpdateFileMetadata<TBot> = (x) => this._client.updateFileMetadata(x)\n public searchFiles: routes.SearchFiles<TBot> = (x) => this._client.searchFiles(x)\n\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public createConversation: routes.CreateConversation<TBot> = (x) => this._client.createConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the conversation creation to an integration.\n */\n public getOrCreateConversation: routes.GetOrCreateConversation<TBot> = (x) => this._client.getOrCreateConversation(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public createUser: routes.CreateUser<TBot> = (x) => this._client.createUser(x)\n /**\n * @deprecated Use `callAction` to delegate the user creation to an integration.\n */\n public getOrCreateUser: routes.GetOrCreateUser<TBot> = (x) => this._client.getOrCreateUser(x)\n}\n", "import { z } from '@bpinternal/zui'\nimport { botIdHeader, configurationHeader, operationHeader, typeHeader } from '../const'\n\nexport const botOperationSchema = z.enum(['event_received', 'register', 'unregister', 'ping', 'action_triggered'])\n\nexport type BotOperation = z.infer<typeof botOperationSchema>\n\nexport type BotContext = {\n botId: string\n type: string\n operation: BotOperation\n configuration: {\n payload: string\n }\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): BotContext => {\n const botId = headers[botIdHeader]\n const base64Configuration = headers[configurationHeader]\n const type = headers[typeHeader]\n const operation = botOperationSchema.parse(headers[operationHeader])\n\n if (!botId) {\n throw new Error('Missing bot headers')\n }\n\n if (!type) {\n throw new Error('Missing type headers')\n }\n\n if (!base64Configuration) {\n throw new Error('Missing configuration headers')\n }\n\n if (!operation) {\n throw new Error('Missing operation headers')\n }\n\n return {\n botId,\n operation,\n type,\n configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { z } from '@bpinternal/zui'\nimport type { Server } from 'node:http'\nimport { SchemaDefinition } from '../schema'\nimport { serve } from '../serve'\nimport { AnyZodObject } from '../type-utils'\nimport { BaseIntegrations } from './generic'\nimport { IntegrationInstance } from './integration-instance'\nimport { botHandler, MessageHandler, EventHandler, StateExpiredHandler, StateType } from './server'\n\ntype BaseStates = Record<string, AnyZodObject>\ntype BaseEvents = Record<string, AnyZodObject>\n\ntype TagDefinition = {\n title?: string\n description?: string\n}\n\ntype StateDefinition<TState extends BaseStates[string]> = SchemaDefinition<TState> & {\n type: StateType\n expiry?: number\n}\n\ntype RecurringEventDefinition<TEvents extends BaseEvents> = {\n [K in keyof TEvents]: {\n type: K\n payload: z.infer<TEvents[K]>\n schedule: { cron: string }\n }\n}[keyof TEvents]\n\ntype EventDefinition<TEvent extends BaseEvents[string]> = SchemaDefinition<TEvent>\n\ntype ConfigurationDefinition = SchemaDefinition\n\ntype UserDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype ConversationDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\ntype MessageDefinition = {\n tags?: Record<string, TagDefinition>\n}\n\nexport type BotProps<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n integrations?: {\n [K in keyof TIntegrations]?: IntegrationInstance<TIntegrations[K]>\n }\n user?: UserDefinition\n conversation?: ConversationDefinition // TODO: add configuration to generic and infer from there\n message?: MessageDefinition\n states?: {\n [K in keyof TStates]: StateDefinition<TStates[K]>\n }\n configuration?: ConfigurationDefinition\n events?: {\n [K in keyof TEvents]: EventDefinition<TEvents[K]>\n }\n recurringEvents?: Record<string, RecurringEventDefinition<TEvents>>\n}\n\ntype BotFrom<TIntegrations extends BaseIntegrations, TStates extends BaseStates, TEvents extends BaseEvents> = {\n integrations: TIntegrations\n states: {\n [K in keyof TStates]: z.infer<TStates[K]>\n }\n events: {\n [K in keyof TEvents]: z.infer<TEvents[K]>\n }\n}\n\ntype BotState<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> = {\n messageHandlers: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n eventHandlers: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n stateExpiredHandlers: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>[]\n}\n\nexport class Bot<\n TIntegrations extends BaseIntegrations = BaseIntegrations,\n TStates extends BaseStates = BaseStates,\n TEvents extends BaseEvents = BaseEvents\n> {\n private _state: BotState<TIntegrations, TStates, TEvents> = {\n messageHandlers: [],\n eventHandlers: [],\n stateExpiredHandlers: [],\n }\n\n public readonly props: BotProps<TIntegrations, TStates, TEvents>\n\n public constructor(props: BotProps<TIntegrations, TStates, TEvents>) {\n this.props = props\n }\n\n public readonly message = (handler: MessageHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.messageHandlers.push(handler)\n }\n public readonly event = (handler: EventHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.eventHandlers.push(handler)\n }\n public readonly stateExpired = (handler: StateExpiredHandler<BotFrom<TIntegrations, TStates, TEvents>>): void => {\n this._state.stateExpiredHandlers.push(handler)\n }\n\n public readonly handler = botHandler(this._state)\n public readonly start = (port?: number): Promise<Server> => serve(this.handler, port)\n}\n"],
5
+ "mappings": "onBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,eAAAC,GAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,eAAAC,GAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,ICAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,IAAAC,GAAkB,2BAClBC,EAAAJ,EAAc,4BAOd,IAAOE,EAAQ,KDNf,IAAMG,EAAiB,IAAE,OAAO,EAAE,IAAI,CAAC,EAEjCC,GAAoB,IAAE,OAAO,CACjC,KAAMD,CACR,CAAC,EAEKE,GAAwB,IAAE,OAAO,CACrC,SAAUF,CACZ,CAAC,EAEKG,GAAqB,IAAE,OAAO,CAClC,SAAUH,CACZ,CAAC,EAEKI,GAAqB,IAAE,OAAO,CAClC,SAAUJ,CACZ,CAAC,EAEKK,GAAqB,IAAE,O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AAN,KAIL,CACQ,OAAoD,CAC1D,gBAAiB,CAAC,EAClB,cAAe,CAAC,EAChB,qBAAsB,CAAC,CACzB,EAEgB,MAET,YAAYC,EAAkD,CACnE,KAAK,MAAQA,CACf,CAEgB,QAAWC,GAA4E,CACrG,KAAK,OAAO,gBAAgB,KAAKA,CAAO,CAC1C,EACgB,MAASA,GAA0E,CACjG,KAAK,OAAO,cAAc,KAAKA,CAAO,CACxC,EACgB,aAAgBA,GAAiF,CAC/G,KAAK,OAAO,qBAAqB,KAAKA,CAAO,CAC/C,EAEgB,QAAUC,GAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
6
6
  "names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "configurationTypeHeader", "integrationIdHeader", "interfaces_exports", "message_exports", "operationHeader", "parseBody", "serve", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "import_zui", "__reExport", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "interfaces_exports", "__export", "creatable", "deletable", "hitl", "listable", "llm", "readable", "schemas_exports", "speechToText", "textToImage", "typingIndicator", "updatable", "schemas_exports", "__export", "speech_to_text_exports", "speech_to_text_exports", "__export", "OpenAITranscribeAudioOutputSchema", "OpenAITranscribeAudioOutputSchema", "zui_default", "import_zui", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationTypeHeader", "configurationHeader", "operationHeader", "typeHeader", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "configurationType", "configurationTypeHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "unique", "array", "pairs", "obj", "mapValues", "obj", "fn", "pairs", "key", "value", "mergeRecords", "a", "b", "merge", "keys", "unique", "result", "aValue", "bValue", "schemaName", "createStore", "props", "mapValues", "e", "k", "isBranded", "schema", "getName", "IntegrationDefinition", "props", "clone", "key", "value", "interfaceDeclaration", "builder", "extensionBuilderOutput", "createStore", "unbrandedEntity", "pairs", "_k", "e", "isBranded", "interfaceTypeArguments", "mapValues", "getName", "resolved", "implementStatement", "self", "mergeRecords", "entityNames", "a", "b", "messages", "InterfaceDeclaration", "props", "entities", "implementStatement", "mapValues", "entity", "actions", "events", "channels", "actionName", "action", "pairs", "resolvedInputSchema", "resolvedOutputSchema", "newActionName", "eventName", "event", "resolvedEventSchema", "newEventName", "channelName", "channel", "messages", "messageName", "message", "resolvedMessageSchema", "generic", "entitySchemas", "entityReferences", "entityName", "zui_default", "name", "templateProps", "import_node_http", "log", "parseBody", "req", "serve", "handler", "port", "callback", "defaultCallback", "server", "res", "request", "mapIncomingMessageToRequest", "response", "e", "log", "incoming", "body", "readBody", "headers", "key", "value", "url", "trimPrefix", "prefix", "resolve", "reject", "chunk", "import_client", "import_client", "retryConfig", "err", "retryCount", "IntegrationSpecificClient", "_client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "vanillaClient", "retryConfig", "client", "IntegrationSpecificClient", "props", "integrationLogger", "response", "onWebhook", "onRegister", "onUnregister", "onMessageCreated", "onActionTriggered", "onPing", "onCreateUser", "onCreateConversation", "thrown", "runtimeError", "_", "incomingRequest", "logger", "parseBody", "webhookUrl", "tags", "channel", "conversation", "user", "type", "payload", "message", "channelHandler", "messageHandler", "input", "action", "output", "IntegrationImplementation", "props", "integrationHandler", "port", "serve", "withUserId", "s", "zui_default", "messageSourceSchema", "messagePayloadSchemas", "defaults", "k", "v", "messageSchema", "hitl", "InterfaceDeclaration", "ToolCallSchema", "zui_default", "ToolChoiceSchema", "MessageSchema", "ModelRefSchema", "ModelSchema", "GenerateContentInputSchema", "modelRefSchema", "GenerateContentInputBaseSchema", "GenerateContentOutputSchema", "llm", "InterfaceDeclaration", "modelRef", "SpeechModelRefSchema", "zui_default", "SpeechToTextModelSchema", "TranscribeAudioInputSchema", "imageModelRefSchema", "TranscribeAudioBaseSchema", "TranscribeAudioOutputSchema", "OpenAITranscribeAudioOutputSchema", "speechToText", "InterfaceDeclaration", "speechToTextModelRef", "baseItem", "zui_default", "withId", "schema", "capitalize", "s", "camelCase", "parts", "first", "rest", "nextToken", "listable", "InterfaceDeclaration", "args", "name", "props", "creatable", "readable", "updatable", "deletable", "ImageModelRefSchema", "zui_default", "ImageModelSchema", "ImageGenerationParamsSchema", "GenerateImageInputSchema", "imageModelRefSchema", "paramsSchema", "GenerateContentInputBaseSchema", "GenerateImageOutputSchema", "textToImage", "InterfaceDeclaration", "imageModelRef", "imageGenerationParams", "typingIndicator", "InterfaceDeclaration", "zui_default", "__reExport", "src_exports", "zui_exports", "import_client", "client", "BotSpecificClient", "_client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "vanillaClient", "retryConfig", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
7
7
  }
@@ -306,6 +306,16 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
306
306
  }>>;
307
307
  userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
308
308
  debug: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
309
+ meta: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{
310
+ promptCategory: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
311
+ integrationName: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
312
+ }, "strip", import("@bpinternal/zui").ZodTypeAny, {
313
+ integrationName?: string | undefined;
314
+ promptCategory?: string | undefined;
315
+ }, {
316
+ integrationName?: string | undefined;
317
+ promptCategory?: string | undefined;
318
+ }>>;
309
319
  }, "strip", import("@bpinternal/zui").ZodTypeAny, {
310
320
  temperature: number;
311
321
  messages: {
@@ -349,6 +359,10 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
349
359
  functionName?: string | undefined;
350
360
  } | undefined;
351
361
  debug?: boolean | undefined;
362
+ meta?: {
363
+ integrationName?: string | undefined;
364
+ promptCategory?: string | undefined;
365
+ } | undefined;
352
366
  }, {
353
367
  messages: {
354
368
  role: "user" | "assistant";
@@ -392,6 +406,10 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
392
406
  functionName?: string | undefined;
393
407
  } | undefined;
394
408
  debug?: boolean | undefined;
409
+ meta?: {
410
+ integrationName?: string | undefined;
411
+ promptCategory?: string | undefined;
412
+ } | undefined;
395
413
  }>;
396
414
  declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
397
415
  id: import("@bpinternal/zui").ZodString;
@@ -724,6 +742,16 @@ export declare const llm: InterfaceDeclaration<{
724
742
  }>>;
725
743
  userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
726
744
  debug: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
745
+ meta: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{
746
+ promptCategory: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
747
+ integrationName: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
748
+ }, "strip", import("@bpinternal/zui").ZodTypeAny, {
749
+ integrationName?: string | undefined;
750
+ promptCategory?: string | undefined;
751
+ }, {
752
+ integrationName?: string | undefined;
753
+ promptCategory?: string | undefined;
754
+ }>>;
727
755
  }, "strip", import("@bpinternal/zui").ZodTypeAny, {
728
756
  temperature: number;
729
757
  messages: {
@@ -765,6 +793,10 @@ export declare const llm: InterfaceDeclaration<{
765
793
  functionName?: string | undefined;
766
794
  } | undefined;
767
795
  debug?: boolean | undefined;
796
+ meta?: {
797
+ integrationName?: string | undefined;
798
+ promptCategory?: string | undefined;
799
+ } | undefined;
768
800
  }, {
769
801
  messages: {
770
802
  role: "user" | "assistant";
@@ -806,6 +838,10 @@ export declare const llm: InterfaceDeclaration<{
806
838
  functionName?: string | undefined;
807
839
  } | undefined;
808
840
  debug?: boolean | undefined;
841
+ meta?: {
842
+ integrationName?: string | undefined;
843
+ promptCategory?: string | undefined;
844
+ } | undefined;
809
845
  }>;
810
846
  listLanguageModels: import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>;
811
847
  }, import("../integration/definition/generic").BaseEvents>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botpress/sdk",
3
- "version": "0.11.6",
3
+ "version": "0.11.7",
4
4
  "description": "Botpress SDK",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -15,7 +15,7 @@
15
15
  "license": "MIT",
16
16
  "dependencies": {
17
17
  "@bpinternal/zui": "0.10.0",
18
- "@botpress/client": "0.31.0"
18
+ "@botpress/client": "0.32.0"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/node": "^18.11.17",