@botpress/sdk 0.8.33 → 0.8.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +3 -3
- package/dist/integration/definition/integration-definition.d.ts +4 -0
- package/dist/integration/definition/interface-declaration.d.ts +20 -9
- package/dist/integration/definition/types.d.ts +4 -1
- package/dist/interfaces/hitl.d.ts +23 -4
- package/dist/interfaces/llm.d.ts +65 -16
- package/dist/utils.d.ts +2 -0
- package/package.json +1 -1
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/sdk@0.8.
|
|
2
|
+
> @botpress/sdk@0.8.35 build /home/runner/work/botpress/botpress/packages/sdk
|
|
3
3
|
> pnpm build:type && pnpm build:node
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @botpress/sdk@0.8.
|
|
6
|
+
> @botpress/sdk@0.8.35 build:type /home/runner/work/botpress/botpress/packages/sdk
|
|
7
7
|
> tsc --emitDeclarationOnly --declaration
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @botpress/sdk@0.8.
|
|
10
|
+
> @botpress/sdk@0.8.35 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 Pe=Object.create;var j=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var H=(t,e)=>{for(var n in e)j(t,n,{get:e[n],enumerable:!0})},F=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Me(e))!Ue.call(t,s)&&s!==n&&j(t,s,{get:()=>e[s],enumerable:!(a=we(e,s))||a.enumerable});return t},g=(t,e,n)=>(F(t,e,"default"),n&&F(n,e,"default")),Y=(t,e,n)=>(n=t!=null?Pe(Ae(t)):{},F(e||!t||!t.__esModule?j(n,"default",{value:t,enumerable:!0}):n,t)),ke=t=>F(j({},"__esModule",{value:!0}),t);var y={};H(y,{Bot:()=>N,BotSpecificClient:()=>A,Integration:()=>K,IntegrationDefinition:()=>C,IntegrationSpecificClient:()=>w,InterfaceDeclaration:()=>h,RuntimeError:()=>_.RuntimeError,botIdHeader:()=>k,botUserIdHeader:()=>V,configurationHeader:()=>R,integrationIdHeader:()=>$,interfaces:()=>Z,isApiError:()=>_.isApiError,messages:()=>L,operationHeader:()=>D,parseBody:()=>f,serve:()=>O,studioComponentDefinitions:()=>ee,typeHeader:()=>J,webhookIdHeader:()=>W});module.exports=ke(y);var L={};H(L,{defaults:()=>Fe});var i={};H(i,{default:()=>o,studioComponentDefinitions:()=>ee});var c=require("@bpinternal/zui");g(i,require("@bpinternal/zui"));var T=c.z.object({allowDynamicVariable:c.z.boolean().optional(),horizontal:c.z.boolean().optional()}),ee={string:{text:{id:"text",params:T.extend({multiLine:c.z.boolean().optional(),growVertically:c.z.boolean().optional(),suggestions:c.z.array(c.z.string()).optional()})},dropdown:{id:"dropdown",params:T.extend({filterable:c.z.boolean().optional()})},radiogroup:{id:"radiogroup",params:T.extend({})},date:{id:"date",params:T.extend({dateFormat:c.z.string().optional(),minDate:c.z.string().optional(),maxDate:c.z.string().optional(),defaultTimezone:c.z.string().optional(),disableTimezoneSelection:c.z.boolean().optional(),highlightCurrentDay:c.z.boolean().optional(),showShortcutButtons:c.z.boolean().optional(),showOutsideDaysOfMonth:c.z.boolean().optional(),firstDayOfWeek:c.z.number().optional(),canChangeMonth:c.z.boolean().optional(),showWeekNumbers:c.z.boolean().optional()})},time:{id:"time",params:T.extend({useAMPM:c.z.boolean().optional(),timeFormat:c.z.string().optional(),minTime:c.z.string().optional(),maxTime:c.z.string().optional(),showArrowButtons:c.z.boolean().optional(),precision:c.z.enum(["minute","second","millisecond"]).optional()})},richtext:{id:"richtext",params:c.z.object({allowDynamicVariable:c.z.boolean().optional(),resizable:c.z.boolean().optional()})},json:{id:"json",params:T.extend({showPreview:c.z.boolean().optional(),showValidationError:c.z.boolean().optional()})},file:{id:"file",params:T.extend({fileTypes:c.z.array(c.z.enum(["image","audio","video"])).optional(),showUploadedFiles:c.z.boolean().optional()})}},number:{number:{id:"number",params:T.extend({allowNumericCharactersOnly:c.z.boolean().optional(),stepSize:c.z.number().optional()})},slider:{id:"slider",params:c.z.object({horizontal:c.z.boolean().optional(),stepSize:c.z.number().optional()})}},boolean:{switch:{id:"switch",params:T}},array:{options:{id:"options",params:T},strings:{id:"strings",params:T},daterange:{id:"daterange",params:c.z.object({dateFormat:c.z.string().optional(),minDate:c.z.string().optional(),maxDate:c.z.string().optional(),defaultTimezone:c.z.string().optional(),allowSingleDayRange:c.z.boolean().optional(),highlightCurrentDay:c.z.boolean().optional(),showOutsideDaysOfMonth:c.z.boolean().optional(),firstDayOfWeek:c.z.number().optional(),canChangeMonth:c.z.boolean().optional(),showWeekNumbers:c.z.boolean().optional()})}},object:{collapsible:{id:"collapsible",params:c.z.object({defaultOpen:c.z.boolean().optional()})},modal:{id:"modal",params:c.z.object({title:c.z.string().optional(),buttonLabel:c.z.string().optional(),closeButtonLabel:c.z.string().optional()})},popover:{id:"popover",params:c.z.object({buttonLabel:c.z.string().optional()})}},discriminatedUnion:{}},o=c.z;var m=i.z.string().min(1),ne=i.z.object({text:m}),oe=i.z.object({markdown:m}),se=i.z.object({imageUrl:m}),ie=i.z.object({audioUrl:m}),ae=i.z.object({videoUrl:m}),re=i.z.object({fileUrl:m,title:m.optional()}),ce=i.z.object({latitude:i.z.number(),longitude:i.z.number(),address:i.z.string().optional(),title:i.z.string().optional()}),le=i.z.object({title:m,subtitle:m.optional(),imageUrl:m.optional(),actions:i.z.array(i.z.object({action:i.z.enum(["postback","url","say"]),label:m,value:m}))}),te=i.z.object({text:m,options:i.z.array(i.z.object({label:m,value:m}))}),Re=i.z.object({items:i.z.array(le)}),De=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("text"),payload:ne}),i.z.object({type:i.z.literal("markdown"),payload:oe}),i.z.object({type:i.z.literal("image"),payload:se}),i.z.object({type:i.z.literal("audio"),payload:ie}),i.z.object({type:i.z.literal("video"),payload:ae}),i.z.object({type:i.z.literal("file"),payload:re}),i.z.object({type:i.z.literal("location"),payload:ce})]),Oe=i.z.object({items:i.z.array(De)}),Fe={text:{schema:ne},markdown:{schema:oe},image:{schema:se},audio:{schema:ie},video:{schema:ae},file:{schema:re},location:{schema:ce},carousel:{schema:Re},card:{schema:le},dropdown:{schema:te},choice:{schema:te},bloc:{schema:Oe}};var Z={};H(Z,{creatable:()=>ze,deletable:()=>Ve,hitl:()=>Ne,listable:()=>Le,llm:()=>Ke,readable:()=>qe,updatable:()=>Ze});var x=t=>Object.entries(t);var S=(t,e)=>Object.fromEntries(x(t).map(([n,a])=>[n,e(a,n)]));var q=Symbol("schemaName"),pe=t=>t?S(t,(n,a)=>({...n,[q]:a})):{},ge=t=>t[q]!==void 0,de=t=>t[q];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.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;events;actions;channels;states;user;secrets;identifier;entities;interfaces={};clone(e){let n=new C({...this,...e});for(let[a,s]of Object.entries(this.interfaces))n.interfaces[a]=s;return n}extend(e,n){let a=n(pe(this.entities)),s=x(a).find(([B,Ee])=>!ge(Ee));if(s)throw new Error(`Cannot extend interface "${e.name}" with entity "${s[0]}"; the provided schema is not part of the integration's entities.`);let r=S(a,B=>({name:de(B),schema:B.schema})),{resolved:l,implementStatement:p}=e.resolve({entities:r}),d=this,{actions:u,events:I}=l;d.actions={...d.actions??{},...u},d.events={...d.events??{},...I};let v=Object.values(r).map(B=>B.name),X=`${e.name}<${v.join(",")}>`;return this.interfaces[X]=p,this}};var h=class{constructor(e){this.props=e;this.name=e.name,this.version=e.version,this.events=e.events,this.actions=e.actions,this.entities=e.entities,this.templateName=e.templateName}name;version;entities;events;actions;templateName;resolve(e){let{entities:n}=e,a={name:this.name,version:this.version,entities:S(n,p=>({name:p.name})),actions:{},events:{}},s={},r={};for(let[p,d]of x(this.actions)){let u=this._dereference(d.input.schema,n),I=this._dereference(d.output.schema,n),v=this._rename(n,p);s[v]={input:{schema:u},output:{schema:I}},a.actions[p]={name:v}}for(let[p,d]of x(this.events)){let u=this._dereference(d.schema,n),I=this._rename(n,p);r[I]={schema:u},a.events[p]={name:I}}return{resolved:{actions:s,events:r},implementStatement:a}}_dereference(e,n){let a={},s={};for(let[r,l]of x(n))a[r]=l.schema,s[r]=o.ref(r);return e(s).dereference(a)}_rename(e,n){if(!this.templateName)return n;let a=S(e,s=>s.name);return this.templateName(n,a)}};var je=o.object({id:o.string(),type:o.enum(["function"]),function:o.object({name:o.string(),arguments:o.record(o.any()).nullable().describe("Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.")})}),He=o.object({type:o.enum(["auto","specific","any","none",""]).optional(),functionName:o.string().optional().describe('Required if `type` is "specific"')}),me=o.object({role:o.enum(["user","assistant"]),type:o.enum(["text","tool_calls","tool_result","multipart"]).default("text"),toolCalls:o.array(je).optional().describe('Required if `type` is "tool_calls"'),toolResultCallId:o.string().optional().describe('Required if `type` is "tool_result"'),content:o.string().or(o.array(o.object({type:o.enum(["text","image"]),mimeType:o.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:o.string().optional().describe('Required if part type is "text" '),url:o.string().optional().describe('Required if part type is "image"')}))).optional().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.')}),ue=o.object({id:o.string()}),he=t=>o.object({model:t.describe("Model to use for content generation"),systemPrompt:o.string().optional().describe("Optional system prompt to guide the model"),messages:o.array(me).describe("Array of messages for the model to process"),responseFormat:o.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:o.number().optional().describe("Maximum number of tokens allowed in the generated response"),temperature:o.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:o.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:o.array(o.string()).max(4).optional().describe("Sequences where the model should stop generating further tokens."),tools:o.array(o.object({type:o.literal("function"),function:o.object({name:o.string(),description:o.string().optional(),inputSchema:o.object({}).passthrough().optional()})})).optional(),toolChoice:He.optional(),userId:o.string().optional()}),Ut=he(ue),Ge=o.object({id:o.string().describe("Response ID from LLM provider"),provider:o.string().describe("LLM provider name"),model:o.string().describe("Model name"),choices:o.array(me.omit({role:!0}).extend({role:o.literal("assistant"),index:o.number().int(),stopReason:o.enum(["stop","max_tokens","tool_calls","content_filter","other"])})),usage:o.object({inputTokens:o.number().int().describe("Number of input tokens used by the model"),inputCost:o.number().describe("Cost of the input tokens received by the model, in U.S. dollars"),outputTokens:o.number().int().describe("Number of output tokens used by the model"),outputCost:o.number().describe("Cost of the output tokens generated by the model, in U.S. dollars")})}),Ke=new h({name:"llm",version:"0.3.0",entities:{model:{schema:ue}},events:{},actions:{generateContent:{input:{schema:({model:t})=>he(t)},output:{schema:()=>Ge}}}});var Ne=new h({name:"hitl",version:"0.0.1",entities:{},events:{},actions:{startHITL:{input:{schema:()=>i.z.object({upstreamConversationId:i.z.string()})},output:{schema:()=>i.z.object({downstreamConversationId:i.z.string()})}}}});var b=o.object({id:o.string()}),E=t=>o.intersection(t,b),_e=t=>t[0].toUpperCase()+t.slice(1),U=(...t)=>{let[e,...n]=t.filter(a=>a.length>0).map(a=>a.toLowerCase());return e?[e,...n.map(_e)].join(""):""},Te=o.string().optional(),Le=new h({name:"listable",version:"0.0.1",entities:{item:{schema:b}},events:{},actions:{list:{input:{schema:()=>o.object({nextToken:Te})},output:{schema:t=>o.object({items:o.array(E(t.item)),meta:o.object({nextToken:Te})})}}},templateName:(t,e)=>U(e.item,t)}),ze=new h({name:"creatable",version:"0.0.1",entities:{item:{schema:b}},events:{created:{schema:t=>o.object({item:E(t.item)})}},actions:{create:{input:{schema:t=>o.object({item:t.item})},output:{schema:t=>o.object({item:E(t.item)})}}},templateName:(t,e)=>U(e.item,t)}),qe=new h({name:"readable",version:"0.0.1",entities:{item:{schema:b}},events:{},actions:{read:{input:{schema:()=>b},output:{schema:t=>o.object({item:E(t.item)})}}},templateName:(t,e)=>U(e.item,t)}),Ze=new h({name:"updatable",version:"0.0.1",entities:{item:{schema:b}},events:{updated:{schema:t=>o.object({item:E(t.item)})}},actions:{update:{input:{schema:t=>b.extend({item:t.item})},output:{schema:t=>o.object({item:E(t.item)})}}},templateName:(t,e)=>U(e.item,t)}),Ve=new h({name:"deletable",version:"0.0.1",entities:{item:{schema:b}},events:{deleted:{schema:()=>b}},actions:{delete:{input:{schema:()=>b},output:{schema:()=>o.object({})}}},templateName:(t,e)=>U(e.item,t)});var k="x-bot-id",V="x-bot-user-id",$="x-integration-id",W="x-webhook-id",R="x-bp-configuration",D="x-bp-operation",J="x-bp-type";var fe=require("node:http");var P=console;function f(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function O(t,e=8072,n=Qe){let a=(0,fe.createServer)(async(s,r)=>{try{let l=await $e(s);if(l.path==="/health"){r.writeHead(200).end("ok");return}let p=await t(l);r.writeHead(p?.status??200,p?.headers??{}).end(p?.body??"{}")}catch(l){P.error("Error while handling request",{error:l?.message??"Internal error occured"}),r.writeHead(500).end(JSON.stringify({error:l?.message??"Internal error occured"}))}});return a.listen(e,()=>n(e)),a}async function $e(t){let e=await Je(t),n={};for(let s=0;s<t.rawHeaders.length;s+=2){let r=t.rawHeaders[s].toLowerCase(),l=t.rawHeaders[s+1];n[r]=l}let a=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:a.pathname,query:We(a.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function We(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function Je(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let a="";t.on("data",s=>a+=s.toString()),t.on("error",s=>n(s)),t.on("end",()=>e(a))})}function Qe(t){P.info(`Listening on port ${t}`)}g(y,i,module.exports);var _=require("@botpress/client");var ye=require("@bpinternal/zui");var Xe=ye.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),be=t=>{let e=t[k],n=t[V],a=t[$],s=t[W],r=t[R],l=Xe.parse(t[D]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!a)throw new Error("Missing integration headers");if(!s)throw new Error("Missing webhook headers");if(!r)throw new Error("Missing configuration headers");if(!l)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:a,webhookId:s,operation:l,configuration:r?JSON.parse(Buffer.from(r,"base64").toString("utf-8")):{}}};var M=require("@botpress/client");var w=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 Q=Y(require("util")),G=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:Q.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return Q.default.format(`[For Bot Owner] ${e}`,...n)}},Ie={forBot:()=>({info:(...t)=>{console.info(G(t))},warn:(...t)=>{console.warn(G(t))},error:(...t)=>{console.error(G(t))},debug:(...t)=>{console.debug(G(t))}})};var ve=t=>async e=>{let n=be(e.headers),a=new w(new M.Client({botId:n.botId,integrationId:n.integrationId})),s={ctx:n,req:e,client:a,logger:Ie,instance:t};try{let r;switch(n.operation){case"webhook_received":r=await et(s);break;case"register":r=await tt(s);break;case"unregister":r=await nt(s);break;case"message_created":r=await it(s);break;case"action_triggered":r=await at(s);break;case"ping":r=await Ye(s);break;case"create_user":r=await ot(s);break;case"create_conversation":r=await st(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return r?{...r,status:r.status??200}:{status:200}}catch(r){if((0,M.isApiError)(r)){let l=new M.RuntimeError(r.message,r);return{status:l.code,body:JSON.stringify(l.toJSON())}}throw r}},Ye=async t=>{},et=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{let{req:r}=f(n);return s.webhook({client:t,ctx:e,req:r,logger:a})},tt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.register)return;let{webhookUrl:r}=f(n);await s.register({client:t,ctx:e,webhookUrl:r,logger:a})},nt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.unregister)return;let{webhookUrl:r}=f(n);await s.unregister({ctx:e,webhookUrl:r,client:t,logger:a})},ot=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createUser)return;let{tags:r}=f(n);return await s.createUser({ctx:e,client:t,tags:r,logger:a})},st=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createConversation)return;let{channel:r,tags:l}=f(n);return await s.createConversation({ctx:e,client:t,channel:r,tags:l,logger:a})},it=async({ctx:t,req:e,client:n,logger:a,instance:s})=>{let{conversation:r,user:l,type:p,payload:d,message:u}=f(e),I=s.channels[r.channel];if(!I)throw new Error(`Channel ${r.channel} not found`);let v=I.messages[p];if(!v)throw new Error(`Message of type ${p} not found in channel ${r.channel}`);await v({ctx:t,conversation:r,message:u,user:l,type:p,client:n,payload:d,ack:async({tags:B})=>{await n.updateMessage({id:u.id,tags:B})},logger:a})},at=async({req:t,ctx:e,client:n,logger:a,instance:s})=>{let{input:r,type:l}=f(t);if(!l)throw new Error("Missing action type");let p=s.actions[l];if(!p)throw new Error(`Action ${l} not found`);let d=await p({ctx:e,input:r,client:n,type:l,logger:a});return{body:JSON.stringify({output:d})}};var K=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=ve(this);start=e=>O(this.handler,e)};var Se=Y(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(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.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 Be=require("@bpinternal/zui");var rt=Be.z.enum(["event_received","register","unregister","ping","action_triggered"]),xe=t=>{let e=t[k],n=t[R],a=t[J],s=rt.parse(t[D]);if(!e)throw new Error("Missing bot headers");if(!a)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!s)throw new Error("Missing operation headers");return{botId:e,operation:s,type:a,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var Ce=t=>async e=>{let n=xe(e.headers);n.operation!=="ping"&&P.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let a=new A(new Se.Client({botId:n.botId})),s={req:e,ctx:n,client:a,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await gt(s);break;case"register":await lt(s);break;case"unregister":await pt(s);break;case"ping":await ct(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},ct=async t=>{},lt=async t=>{},pt=async t=>{},gt=async({ctx:t,req:e,client:n,instance:a})=>{P.debug(`Received event ${t.type}`);let s=f(e),r=s.event;switch(t.type){case"message_created":let l={user:r.payload.user,conversation:r.payload.conversation,message:r.payload.message,states:r.payload.states,event:r};await Promise.all(a.messageHandlers.map(u=>u({client:n,ctx:t,...l})));break;case"state_expired":let p={state:r.payload.state};await Promise.all(a.stateExpiredHandlers.map(u=>u({client:n,ctx:t,...p})));break;default:let d={event:s.event};await Promise.all(a.eventHandlers.map(u=>u({client:n,ctx:t,...d})))}};var N=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=Ce(this._state);start=e=>O(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,interfaces,isApiError,messages,operationHeader,parseBody,serve,studioComponentDefinitions,typeHeader,webhookIdHeader});
|
|
1
|
+
"use strict";var we=Object.create;var H=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var N=(t,e)=>{for(var n in e)H(t,n,{get:e[n],enumerable:!0})},F=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ae(e))!ke.call(t,i)&&i!==n&&H(t,i,{get:()=>e[i],enumerable:!(r=Me(e,i))||r.enumerable});return t},m=(t,e,n)=>(F(t,e,"default"),n&&F(n,e,"default")),ne=(t,e,n)=>(n=t!=null?we(Re(t)):{},F(e||!t||!t.__esModule?H(n,"default",{value:t,enumerable:!0}):n,t)),Ue=t=>F(H({},"__esModule",{value:!0}),t);var I={};N(I,{Bot:()=>z,BotSpecificClient:()=>A,Integration:()=>_,IntegrationDefinition:()=>C,IntegrationSpecificClient:()=>w,InterfaceDeclaration:()=>T,RuntimeError:()=>L.RuntimeError,botIdHeader:()=>U,botUserIdHeader:()=>Q,configurationHeader:()=>D,integrationIdHeader:()=>X,interfaces:()=>J,isApiError:()=>L.isApiError,messages:()=>K,operationHeader:()=>O,parseBody:()=>b,serve:()=>j,studioComponentDefinitions:()=>se,typeHeader:()=>ee,webhookIdHeader:()=>Y});module.exports=Ue(I);var K={};N(K,{defaults:()=>V});var o={};N(o,{default:()=>s,studioComponentDefinitions:()=>se});var c=require("@bpinternal/zui");m(o,require("@bpinternal/zui"));var y=c.z.object({allowDynamicVariable:c.z.boolean().optional(),horizontal:c.z.boolean().optional()}),se={string:{text:{id:"text",params:y.extend({multiLine:c.z.boolean().optional(),growVertically:c.z.boolean().optional(),suggestions:c.z.array(c.z.string()).optional()})},dropdown:{id:"dropdown",params:y.extend({filterable:c.z.boolean().optional()})},radiogroup:{id:"radiogroup",params:y.extend({})},date:{id:"date",params:y.extend({dateFormat:c.z.string().optional(),minDate:c.z.string().optional(),maxDate:c.z.string().optional(),defaultTimezone:c.z.string().optional(),disableTimezoneSelection:c.z.boolean().optional(),highlightCurrentDay:c.z.boolean().optional(),showShortcutButtons:c.z.boolean().optional(),showOutsideDaysOfMonth:c.z.boolean().optional(),firstDayOfWeek:c.z.number().optional(),canChangeMonth:c.z.boolean().optional(),showWeekNumbers:c.z.boolean().optional()})},time:{id:"time",params:y.extend({useAMPM:c.z.boolean().optional(),timeFormat:c.z.string().optional(),minTime:c.z.string().optional(),maxTime:c.z.string().optional(),showArrowButtons:c.z.boolean().optional(),precision:c.z.enum(["minute","second","millisecond"]).optional()})},richtext:{id:"richtext",params:c.z.object({allowDynamicVariable:c.z.boolean().optional(),resizable:c.z.boolean().optional()})},json:{id:"json",params:y.extend({showPreview:c.z.boolean().optional(),showValidationError:c.z.boolean().optional()})},file:{id:"file",params:y.extend({fileTypes:c.z.array(c.z.enum(["image","audio","video"])).optional(),showUploadedFiles:c.z.boolean().optional()})}},number:{number:{id:"number",params:y.extend({allowNumericCharactersOnly:c.z.boolean().optional(),stepSize:c.z.number().optional()})},slider:{id:"slider",params:c.z.object({horizontal:c.z.boolean().optional(),stepSize:c.z.number().optional()})}},boolean:{switch:{id:"switch",params:y}},array:{options:{id:"options",params:y},strings:{id:"strings",params:y},daterange:{id:"daterange",params:c.z.object({dateFormat:c.z.string().optional(),minDate:c.z.string().optional(),maxDate:c.z.string().optional(),defaultTimezone:c.z.string().optional(),allowSingleDayRange:c.z.boolean().optional(),highlightCurrentDay:c.z.boolean().optional(),showOutsideDaysOfMonth:c.z.boolean().optional(),firstDayOfWeek:c.z.number().optional(),canChangeMonth:c.z.boolean().optional(),showWeekNumbers:c.z.boolean().optional()})}},object:{collapsible:{id:"collapsible",params:c.z.object({defaultOpen:c.z.boolean().optional()})},modal:{id:"modal",params:c.z.object({title:c.z.string().optional(),buttonLabel:c.z.string().optional(),closeButtonLabel:c.z.string().optional()})},popover:{id:"popover",params:c.z.object({buttonLabel:c.z.string().optional()})}},discriminatedUnion:{}},s=c.z;var h=o.z.string().min(1),ie=o.z.object({text:h}),ae=o.z.object({markdown:h}),re=o.z.object({imageUrl:h}),ce=o.z.object({audioUrl:h}),le=o.z.object({videoUrl:h}),pe=o.z.object({fileUrl:h,title:h.optional()}),ge=o.z.object({latitude:o.z.number(),longitude:o.z.number(),address:o.z.string().optional(),title:o.z.string().optional()}),de=o.z.object({title:h,subtitle:h.optional(),imageUrl:h.optional(),actions:o.z.array(o.z.object({action:o.z.enum(["postback","url","say"]),label:h,value:h}))}),oe=o.z.object({text:h,options:o.z.array(o.z.object({label:h,value:h}))}),De=o.z.object({items:o.z.array(de)}),Oe=o.z.discriminatedUnion("type",[o.z.object({type:o.z.literal("text"),payload:ie}),o.z.object({type:o.z.literal("markdown"),payload:ae}),o.z.object({type:o.z.literal("image"),payload:re}),o.z.object({type:o.z.literal("audio"),payload:ce}),o.z.object({type:o.z.literal("video"),payload:le}),o.z.object({type:o.z.literal("file"),payload:pe}),o.z.object({type:o.z.literal("location"),payload:ge})]),je=o.z.object({items:o.z.array(Oe)}),V={text:{schema:ie},markdown:{schema:ae},image:{schema:re},audio:{schema:ce},video:{schema:le},file:{schema:pe},location:{schema:ge},carousel:{schema:De},card:{schema:de},dropdown:{schema:oe},choice:{schema:oe},bloc:{schema:je}};var J={};N(J,{creatable:()=>Ve,deletable:()=>We,hitl:()=>ze,listable:()=>qe,llm:()=>_e,readable:()=>Ze,updatable:()=>$e});var Fe=t=>Array.from(new Set(t)),B=t=>Object.entries(t);var S=(t,e)=>Object.fromEntries(B(t).map(([n,r])=>[n,e(r,n)])),R=(t,e,n)=>{let r=Fe([...Object.keys(t),...Object.keys(e)]),i={};for(let a of r){let l=t[a],g=e[a];l&&g?i[a]=n(l,g):l?i[a]=l:g&&(i[a]=g)}return i};var $=Symbol("schemaName"),me=t=>t?S(t,(n,r)=>({...n,[$]:r})):{},ue=t=>t[$]!==void 0,he=t=>t[$];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.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;events;actions;channels;states;user;secrets;identifier;entities;interfaces={};clone(e){let n=new C({...this,...e});for(let[r,i]of Object.entries(this.interfaces))n.interfaces[r]=i;return n}extend(e,n){let r=n(me(this.entities)),i=B(r).find(([u,x])=>!ue(x));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=S(r,u=>({name:he(u),schema:u.schema})),{resolved:l,implementStatement:g}=e.resolve({entities:a}),p=this;p.actions=R(p.actions??{},l.actions,this._mergeActions),p.channels=R(p.channels??{},l.channels,this._mergeChannels),p.events=R(p.events??{},l.events,this._mergeEvents);let d=Object.values(a).map(u=>u.name),f=`${e.name}<${d.join(",")}>`;return this.interfaces[f]=g,this}_mergeActions=(e,n)=>({title:n.title??e.title,description:n.description??e.description,input:{schema:e.input.schema.merge(n.input.schema)},output:{schema:e.output.schema.merge(n.output.schema)}});_mergeEvents=(e,n)=>({title:n.title??e.title,description:n.description??e.description,schema:e.schema.merge(n.schema)});_mergeChannels=(e,n)=>{let r=R(e.messages,n.messages,this._mergeMessage);return{title:n.title??e.title,description:n.description??e.description,conversation:n.conversation??e.conversation,message:n.message??e.message,messages:r}};_mergeMessage=(e,n)=>({schema:e.schema.merge(n.schema)})};var T=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:n}=e,r={name:this.name,version:this.version,entities:S(n,p=>({name:p.name})),actions:{},events:{}},i={},a={},l={};for(let[p,d]of B(this.actions)){let f=this._dereference(d.input.schema,n),u=this._dereference(d.output.schema,n),x=this._rename(n,p);i[x]={input:{schema:f},output:{schema:u}},r.actions[p]={name:x}}for(let[p,d]of B(this.events)){let f=this._dereference(d.schema,n),u=this._rename(n,p);a[u]={schema:f},r.events[p]={name:u}}for(let[p,d]of B(this.channels)){let f={};for(let[u,x]of B(d.messages)){let q=this._dereference(x.schema,n);f[u]={schema:q}}l[p]={messages:f}}return{resolved:{actions:i,events:a,channels:l},implementStatement:r}}_dereference(e,n){let r={},i={};for(let[a,l]of B(n))r[a]=l.schema,i[a]=s.ref(a);return e(i).dereference(r)}_rename(e,n){if(!this.templateName)return n;let r=S(e,i=>i.name);return this.templateName(n,r)}};var He=s.object({id:s.string(),type:s.enum(["function"]),function:s.object({name:s.string(),arguments:s.record(s.any()).nullable().describe("Some LLMs may generate invalid JSON for a tool call, so this will be `null` when it happens.")})}),Ne=s.object({type:s.enum(["auto","specific","any","none",""]).optional(),functionName:s.string().optional().describe('Required if `type` is "specific"')}),Te=s.object({role:s.enum(["user","assistant"]),type:s.enum(["text","tool_calls","tool_result","multipart"]).default("text"),toolCalls:s.array(He).optional().describe('Required if `type` is "tool_calls"'),toolResultCallId:s.string().optional().describe('Required if `type` is "tool_result"'),content:s.string().or(s.array(s.object({type:s.enum(["text","image"]),mimeType:s.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:s.string().optional().describe('Required if part type is "text" '),url:s.string().optional().describe('Required if part type is "image"')}))).optional().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.')}),W=s.object({id:s.string()}),Ke=W.extend({name:s.string(),input:s.object({maxTokens:s.number().int(),costPer1MTokens:s.number()}),output:s.object({maxTokens:s.number().int(),costPer1MTokens:s.number()})}),fe=t=>s.object({model:t.describe("Model to use for content generation").optional(),systemPrompt:s.string().optional().describe("Optional system prompt to guide the model"),messages:s.array(Te).describe("Array of messages for the model to process"),responseFormat:s.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:s.number().optional().describe("Maximum number of tokens allowed in the generated response"),temperature:s.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:s.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:s.array(s.string()).max(4).optional().describe("Sequences where the model should stop generating further tokens."),tools:s.array(s.object({type:s.literal("function"),function:s.object({name:s.string(),description:s.string().optional(),inputSchema:s.object({}).passthrough().optional()})})).optional(),toolChoice:Ne.optional(),userId:s.string().optional()}),Ut=fe(W),Ge=s.object({id:s.string().describe("Response ID from LLM provider"),provider:s.string().describe("LLM provider name"),model:s.string().describe("Model name"),choices:s.array(Te.omit({role:!0}).extend({role:s.literal("assistant"),index:s.number().int(),stopReason:s.enum(["stop","max_tokens","tool_calls","content_filter","other"])})),usage:s.object({inputTokens:s.number().int().describe("Number of input tokens used by the model"),inputCost:s.number().describe("Cost of the input tokens received by the model, in U.S. dollars"),outputTokens:s.number().int().describe("Number of output tokens used by the model"),outputCost:s.number().describe("Cost of the output tokens generated by the model, in U.S. dollars")})}),_e=new T({name:"llm",version:"1.0.0",entities:{modelRef:{schema:W}},events:{},actions:{generateContent:{input:{schema:({modelRef:t})=>fe(t)},output:{schema:()=>Ge}},listModels:{input:{schema:()=>s.object({})},output:{schema:({modelRef:t})=>s.object({models:s.array(s.intersection(Ke,t))})}}}});var ze=new T({name:"hitl",version:"0.0.1",entities:{},events:{},actions:{createUser:{input:{schema:()=>o.z.object({name:o.z.string().optional(),pictureUrl:o.z.string().optional(),email:o.z.string().optional()})},output:{schema:()=>o.z.object({userId:o.z.string()})}},openTicket:{input:{schema:()=>o.z.object({userId:o.z.string(),title:o.z.string(),description:o.z.string().optional()})},output:{schema:()=>o.z.object({conversationId:o.z.string()})}}},channels:{ticket:{messages:{text:{schema:()=>V.text.schema.extend({userId:o.z.string().optional().describe("Allows sending a message pretending to be a certain user")})}}}}});var v=s.object({id:s.string()}),E=t=>s.intersection(t,v),Le=t=>t[0].toUpperCase()+t.slice(1),k=(...t)=>{let[e,...n]=t.filter(r=>r.length>0).map(r=>r.toLowerCase());return e?[e,...n.map(Le)].join(""):""},ye=s.string().optional(),qe=new T({name:"listable",version:"0.0.1",entities:{item:{schema:v}},events:{},actions:{list:{input:{schema:()=>s.object({nextToken:ye})},output:{schema:t=>s.object({items:s.array(E(t.item)),meta:s.object({nextToken:ye})})}}},templateName:(t,e)=>k(e.item,t)}),Ve=new T({name:"creatable",version:"0.0.1",entities:{item:{schema:v}},events:{created:{schema:t=>s.object({item:E(t.item)})}},actions:{create:{input:{schema:t=>s.object({item:t.item})},output:{schema:t=>s.object({item:E(t.item)})}}},templateName:(t,e)=>k(e.item,t)}),Ze=new T({name:"readable",version:"0.0.1",entities:{item:{schema:v}},events:{},actions:{read:{input:{schema:()=>v},output:{schema:t=>s.object({item:E(t.item)})}}},templateName:(t,e)=>k(e.item,t)}),$e=new T({name:"updatable",version:"0.0.1",entities:{item:{schema:v}},events:{updated:{schema:t=>s.object({item:E(t.item)})}},actions:{update:{input:{schema:t=>v.extend({item:t.item})},output:{schema:t=>s.object({item:E(t.item)})}}},templateName:(t,e)=>k(e.item,t)}),We=new T({name:"deletable",version:"0.0.1",entities:{item:{schema:v}},events:{deleted:{schema:()=>v}},actions:{delete:{input:{schema:()=>v},output:{schema:()=>s.object({})}}},templateName:(t,e)=>k(e.item,t)});var U="x-bot-id",Q="x-bot-user-id",X="x-integration-id",Y="x-webhook-id",D="x-bp-configuration",O="x-bp-operation",ee="x-bp-type";var be=require("node:http");var P=console;function b(t){if(!t.body)throw new Error("Missing body");return JSON.parse(t.body)}async function j(t,e=8072,n=Ye){let r=(0,be.createServer)(async(i,a)=>{try{let l=await Je(i);if(l.path==="/health"){a.writeHead(200).end("ok");return}let g=await t(l);a.writeHead(g?.status??200,g?.headers??{}).end(g?.body??"{}")}catch(l){P.error("Error while handling request",{error:l?.message??"Internal error occured"}),a.writeHead(500).end(JSON.stringify({error:l?.message??"Internal error occured"}))}});return r.listen(e,()=>n(e)),r}async function Je(t){let e=await Xe(t),n={};for(let i=0;i<t.rawHeaders.length;i+=2){let a=t.rawHeaders[i].toLowerCase(),l=t.rawHeaders[i+1];n[a]=l}let r=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:r.pathname,query:Qe(r.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function Qe(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function Xe(t){return new Promise((e,n)=>{if(t.method!=="POST"&&t.method!=="PUT"&&t.method!=="PATCH")return e(void 0);let r="";t.on("data",i=>r+=i.toString()),t.on("error",i=>n(i)),t.on("end",()=>e(r))})}function Ye(t){P.info(`Listening on port ${t}`)}m(I,o,module.exports);var L=require("@botpress/client");var Ie=require("@bpinternal/zui");var et=Ie.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),ve=t=>{let e=t[U],n=t[Q],r=t[X],i=t[Y],a=t[D],l=et.parse(t[O]);if(!e)throw new Error("Missing bot headers");if(!n)throw new Error("Missing bot user headers");if(!r)throw new Error("Missing integration headers");if(!i)throw new Error("Missing webhook headers");if(!a)throw new Error("Missing configuration headers");if(!l)throw new Error("Missing operation headers");return{botId:e,botUserId:n,integrationId:r,webhookId:i,operation:l,configuration:a?JSON.parse(Buffer.from(a,"base64").toString("utf-8")):{}}};var M=require("@botpress/client");var w=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 te=ne(require("util")),G=t=>{if(process.env.BP_LOG_FORMAT==="json")return JSON.stringify({msg:te.default.format(...t),visible_to_bot_owner:!0});{let[e,...n]=t;return te.default.format(`[For Bot Owner] ${e}`,...n)}},Be={forBot:()=>({info:(...t)=>{console.info(G(t))},warn:(...t)=>{console.warn(G(t))},error:(...t)=>{console.error(G(t))},debug:(...t)=>{console.debug(G(t))}})};var xe=t=>async e=>{let n=ve(e.headers),r=new w(new M.Client({botId:n.botId,integrationId:n.integrationId})),i={ctx:n,req:e,client:r,logger:Be,instance:t};try{let a;switch(n.operation){case"webhook_received":a=await nt(i);break;case"register":a=await st(i);break;case"unregister":a=await ot(i);break;case"message_created":a=await rt(i);break;case"action_triggered":a=await ct(i);break;case"ping":a=await tt(i);break;case"create_user":a=await it(i);break;case"create_conversation":a=await at(i);break;default:throw new Error(`Unknown operation ${n.operation}`)}return a?{...a,status:a.status??200}:{status:200}}catch(a){if((0,M.isApiError)(a)){let l=new M.RuntimeError(a.message,a);return{status:l.code,body:JSON.stringify(l.toJSON())}}throw a}},tt=async t=>{},nt=async({client:t,ctx:e,req:n,logger:r,instance:i})=>{let{req:a}=b(n);return i.webhook({client:t,ctx:e,req:a,logger:r})},st=async({client:t,ctx:e,req:n,logger:r,instance:i})=>{if(!i.register)return;let{webhookUrl:a}=b(n);await i.register({client:t,ctx:e,webhookUrl:a,logger:r})},ot=async({client:t,ctx:e,req:n,logger:r,instance:i})=>{if(!i.unregister)return;let{webhookUrl:a}=b(n);await i.unregister({ctx:e,webhookUrl:a,client:t,logger:r})},it=async({client:t,ctx:e,req:n,logger:r,instance:i})=>{if(!i.createUser)return;let{tags:a}=b(n);return await i.createUser({ctx:e,client:t,tags:a,logger:r})},at=async({client:t,ctx:e,req:n,logger:r,instance:i})=>{if(!i.createConversation)return;let{channel:a,tags:l}=b(n);return await i.createConversation({ctx:e,client:t,channel:a,tags:l,logger:r})},rt=async({ctx:t,req:e,client:n,logger:r,instance:i})=>{let{conversation:a,user:l,type:g,payload:p,message:d}=b(e),f=i.channels[a.channel];if(!f)throw new Error(`Channel ${a.channel} not found`);let u=f.messages[g];if(!u)throw new Error(`Message of type ${g} not found in channel ${a.channel}`);await u({ctx:t,conversation:a,message:d,user:l,type:g,client:n,payload:p,ack:async({tags:q})=>{await n.updateMessage({id:d.id,tags:q})},logger:r})},ct=async({req:t,ctx:e,client:n,logger:r,instance:i})=>{let{input:a,type:l}=b(t);if(!l)throw new Error("Missing action type");let g=i.actions[l];if(!g)throw new Error(`Action ${l} not found`);let p=await g({ctx:e,input:a,client:n,type:l,logger:r});return{body:JSON.stringify({output:p})}};var _=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=xe(this);start=e=>j(this.handler,e)};var Ee=ne(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(n=>({state:{...n.state,payload:n.state.payload}}));setState=e=>this.client.setState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));getOrSetState=e=>this.client.getOrSetState(e).then(n=>({state:{...n.state,payload:n.state.payload}}));patchState=e=>this.client.patchState(e).then(n=>({state:{...n.state,payload:n.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 Se=require("@bpinternal/zui");var lt=Se.z.enum(["event_received","register","unregister","ping","action_triggered"]),Ce=t=>{let e=t[U],n=t[D],r=t[ee],i=lt.parse(t[O]);if(!e)throw new Error("Missing bot headers");if(!r)throw new Error("Missing type headers");if(!n)throw new Error("Missing configuration headers");if(!i)throw new Error("Missing operation headers");return{botId:e,operation:i,type:r,configuration:n?JSON.parse(Buffer.from(n,"base64").toString("utf-8")):{}}};var Pe=t=>async e=>{let n=Ce(e.headers);n.operation!=="ping"&&P.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let r=new A(new Ee.Client({botId:n.botId})),i={req:e,ctx:n,client:r,instance:t};switch(n.operation){case"action_triggered":throw new Error(`Operation ${n.operation} not supported yet`);case"event_received":await mt(i);break;case"register":await gt(i);break;case"unregister":await dt(i);break;case"ping":await pt(i);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},pt=async t=>{},gt=async t=>{},dt=async t=>{},mt=async({ctx:t,req:e,client:n,instance:r})=>{P.debug(`Received event ${t.type}`);let i=b(e),a=i.event;switch(t.type){case"message_created":let l={user:a.payload.user,conversation:a.payload.conversation,message:a.payload.message,states:a.payload.states,event:a};await Promise.all(r.messageHandlers.map(d=>d({client:n,ctx:t,...l})));break;case"state_expired":let g={state:a.payload.state};await Promise.all(r.stateExpiredHandlers.map(d=>d({client:n,ctx:t,...g})));break;default:let p={event:i.event};await Promise.all(r.eventHandlers.map(d=>d({client:n,ctx:t,...p})))}};var z=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=Pe(this._state);start=e=>j(this.handler,e)};0&&(module.exports={Bot,BotSpecificClient,Integration,IntegrationDefinition,IntegrationSpecificClient,InterfaceDeclaration,RuntimeError,botIdHeader,botUserIdHeader,configurationHeader,integrationIdHeader,interfaces,isApiError,messages,operationHeader,parseBody,serve,studioComponentDefinitions,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/utils.ts", "../src/integration/definition/branded-schema.ts", "../src/integration/definition/integration-definition.ts", "../src/integration/definition/interface-declaration.ts", "../src/interfaces/llm.ts", "../src/interfaces/hitl.ts", "../src/interfaces/sync.ts", "../src/const.ts", "../src/serve.ts", "../src/log.ts", "../src/integration/context.ts", "../src/integration/server.ts", "../src/integration/client/index.ts", "../src/integration/logger.ts", "../src/integration/implementation.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 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, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n text: {\n id: 'text',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n date: {\n id: 'date',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n time: {\n id: 'time',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n richtext: {\n id: 'richtext',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n json: {\n id: 'json',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n file: {\n id: 'file',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n number: {\n id: 'number',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n options: {\n id: 'options',\n params: commonInputParams,\n },\n strings: {\n id: 'strings',\n params: commonInputParams,\n },\n daterange: {\n id: 'daterange',\n params: z.object({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n allowSingleDayRange: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n modal: {\n id: 'modal',\n params: z.object({\n title: z.string().optional(),\n buttonLabel: z.string().optional(),\n closeButtonLabel: z.string().optional(),\n }),\n },\n popover: {\n id: 'popover',\n params: z.object({\n buttonLabel: z.string().optional(),\n }),\n },\n },\n discriminatedUnion: {},\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\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 * from './llm'\nexport * from './hitl'\nexport * from './sync'\n", "export 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", "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 } 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 InterfaceImplementationStatement,\n} from './types'\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\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 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 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 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<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\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.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, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities> {\n const clone = new IntegrationDefinition<TConfig, 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 const { actions, events } = resolved\n self.actions = { ...(self.actions ?? {}), ...actions }\n self.events = { ...(self.events ?? {}), ...events }\n\n const entityNames = Object.values(interfaceTypeArguments).map((e) => e.name)\n const key = `${interfaceDeclaration.name}<${entityNames.join(',')}>`\n this.interfaces[key] = implementStatement\n\n return this\n }\n}\n", "import * as utils from '../../utils'\nimport z, { AnyZodObject, GenericZuiSchema, ZodRef } from '../../zui'\nimport { BaseActions, BaseEntities, BaseEvents } from './generic'\nimport {\n ActionDefinition,\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 GenericActionDefinition<\n TEntities extends BaseEntities,\n TAction extends BaseActions[string] = BaseActions[string]\n> = {\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> = {\n name: string\n version: string\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 entities: {\n [K in keyof TEntities]: EntityDefinition<TEntities[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: this['props']['entities']\n public readonly events: this['props']['events']\n public readonly actions: this['props']['actions']\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.events = props.events\n this.actions = props.actions\n this.entities = props.entities\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\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 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] = { schema: resolvedEventSchema }\n implementStatement.events[eventName] = { name: newEventName }\n }\n\n const resolved = {\n actions,\n events,\n } as ResolvedInterface<TActions, TEvents>\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 { 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 .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 ModelSchema = z.object({ id: z.string() })\n\nconst GenerateContentInputSchema = <S extends z.ZodSchema>(modelSchema: S) =>\n z.object({\n model: modelSchema.describe('Model to use for content generation'),\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(),\n description: z.string().optional(),\n inputSchema: z.object({}).passthrough().optional(),\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 })\n\nconst GenerateContentInputBaseSchema = GenerateContentInputSchema(ModelSchema)\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})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '0.3.0',\n entities: {\n model: {\n schema: ModelSchema,\n },\n },\n events: {},\n actions: {\n generateContent: {\n input: {\n schema: ({ model }) => GenerateContentInputSchema(model),\n },\n output: {\n schema: () => GenerateContentOutputSchema,\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}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport { z } from '../zui'\n\nexport const hitl = new InterfaceDeclaration({\n name: 'hitl',\n version: '0.0.1',\n entities: {},\n events: {},\n actions: {\n startHITL: {\n input: {\n schema: () => z.object({ upstreamConversationId: z.string() }),\n },\n output: {\n schema: () => z.object({ downstreamConversationId: z.string() }),\n },\n },\n },\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", "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 configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\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 { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\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\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\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 configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\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['configuration']>\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 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(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\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 return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n throw thrown\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 { 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", "/* eslint-disable no-console */\nimport 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 * as client from '@botpress/client'\nimport { log } from '../log'\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 botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\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) => 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) => 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) => 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.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).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": "mnBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,SAAAE,EAAA,sBAAAC,EAAA,gBAAAC,EAAA,0BAAAC,EAAA,8BAAAC,EAAA,yBAAAC,EAAA,gDAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,wBAAAC,EAAA,eAAAC,EAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,+BAAAC,GAAA,eAAAC,EAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,KCAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,+BAAAC,KAAA,IAAAC,EAAiF,2BACjFC,EAAAL,EAAc,4BAEd,IAAMM,EAAoB,IAAE,OAAO,CACjC,qBAAsB,IAAE,QAAQ,EAAE,SAAS,EAC3C,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,CAAC,EAEYH,GAA6B,CACxC,OAAQ,CACN,KAAM,CACJ,GAAI,OACJ,OAAQG,EAAkB,OAAO,CAC/B,UAAW,IAAE,QA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AAX,EACA,GAAGe,CACL,CAAC,CACH,CACF,EACA,MACF,IAAK,gBACH,IAAME,EAAoC,CAAE,MAAOH,EAAM,QAAQ,KAAM,EACvE,MAAM,QAAQ,IACZhB,EAAS,qBAAqB,IAAKkB,GACjCA,EAAQ,CACN,OAAAL,EACA,IAAAX,EACA,GAAGiB,CACL,CAAC,CACH,CACF,EACA,MACF,QACE,IAAMC,EAAe,CAAE,MAAON,EAAK,KAAM,EACzC,MAAM,QAAQ,IACZd,EAAS,cAAc,IAAKkB,GAC1BA,EAAQ,CACN,OAAAL,EACA,IAAAX,EACA,GAAGkB,CACL,CAAC,CACH,CACF,CACJ,CACF,EG1DO,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",
|
|
6
|
-
"names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "interfaces_exports", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "interfaces_exports", "__export", "creatable", "deletable", "hitl", "listable", "llm", "readable", "updatable", "pairs", "obj", "mapValues", "obj", "fn", "pairs", "key", "value", "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", "
|
|
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 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, type UIComponentDefinitions, type DefaultComponentDefinitions } from '@bpinternal/zui'\nexport * from '@bpinternal/zui'\n\nconst commonInputParams = z.object({\n allowDynamicVariable: z.boolean().optional(),\n horizontal: z.boolean().optional(),\n})\n\nexport const studioComponentDefinitions = {\n string: {\n text: {\n id: 'text',\n params: commonInputParams.extend({\n multiLine: z.boolean().optional(),\n growVertically: z.boolean().optional(),\n suggestions: z.array(z.string()).optional(),\n }),\n },\n dropdown: {\n id: 'dropdown',\n params: commonInputParams.extend({\n filterable: z.boolean().optional(),\n }),\n },\n radiogroup: {\n id: 'radiogroup',\n params: commonInputParams.extend({}),\n },\n date: {\n id: 'date',\n params: commonInputParams.extend({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n disableTimezoneSelection: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showShortcutButtons: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n time: {\n id: 'time',\n params: commonInputParams.extend({\n useAMPM: z.boolean().optional(),\n timeFormat: z.string().optional(),\n minTime: z.string().optional(),\n maxTime: z.string().optional(),\n showArrowButtons: z.boolean().optional(),\n precision: z.enum(['minute', 'second', 'millisecond']).optional(),\n }),\n },\n richtext: {\n id: 'richtext',\n params: z.object({\n allowDynamicVariable: z.boolean().optional(),\n resizable: z.boolean().optional(),\n }),\n },\n json: {\n id: 'json',\n params: commonInputParams.extend({\n showPreview: z.boolean().optional(),\n showValidationError: z.boolean().optional(),\n }),\n },\n file: {\n id: 'file',\n params: commonInputParams.extend({\n fileTypes: z.array(z.enum(['image', 'audio', 'video'])).optional(),\n showUploadedFiles: z.boolean().optional(),\n }),\n },\n },\n number: {\n number: {\n id: 'number',\n params: commonInputParams.extend({\n allowNumericCharactersOnly: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n slider: {\n id: 'slider',\n params: z.object({\n horizontal: z.boolean().optional(),\n stepSize: z.number().optional(),\n }),\n },\n },\n boolean: {\n switch: {\n id: 'switch',\n params: commonInputParams,\n },\n },\n array: {\n options: {\n id: 'options',\n params: commonInputParams,\n },\n strings: {\n id: 'strings',\n params: commonInputParams,\n },\n daterange: {\n id: 'daterange',\n params: z.object({\n dateFormat: z.string().optional(),\n minDate: z.string().optional(),\n maxDate: z.string().optional(),\n defaultTimezone: z.string().optional(),\n allowSingleDayRange: z.boolean().optional(),\n highlightCurrentDay: z.boolean().optional(),\n showOutsideDaysOfMonth: z.boolean().optional(),\n firstDayOfWeek: z.number().optional(),\n canChangeMonth: z.boolean().optional(),\n showWeekNumbers: z.boolean().optional(),\n }),\n },\n },\n object: {\n collapsible: {\n id: 'collapsible',\n params: z.object({\n defaultOpen: z.boolean().optional(),\n }),\n },\n modal: {\n id: 'modal',\n params: z.object({\n title: z.string().optional(),\n buttonLabel: z.string().optional(),\n closeButtonLabel: z.string().optional(),\n }),\n },\n popover: {\n id: 'popover',\n params: z.object({\n buttonLabel: z.string().optional(),\n }),\n },\n },\n discriminatedUnion: {},\n} as const satisfies UIComponentDefinitions\n\nexport type UI<Namespace extends 'studio' | 'dashboard' = 'studio'> = Namespace extends 'studio'\n ? typeof studioComponentDefinitions\n : Namespace extends 'dashboard'\n ? DefaultComponentDefinitions\n : any\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 * from './llm'\nexport * from './hitl'\nexport * from './sync'\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 } 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} from './types'\n\nexport type IntegrationDefinitionProps<\n TConfig extends BaseConfig = BaseConfig,\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 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 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 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<TConfig, TEvents, TActions, TChannels, TStates, TEntities>\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.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, TEvents, TActions, TChannels, TStates, TEntities>>\n ): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities> {\n const clone = new IntegrationDefinition<TConfig, 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 const key = `${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 title: b.title ?? a.title,\n description: b.description ?? a.description,\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 title: b.title ?? a.title,\n description: b.description ?? a.description,\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 title: b.title ?? a.title,\n description: b.description ?? a.description,\n conversation: b.conversation ?? a.conversation,\n message: b.message ?? a.message,\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 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 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] = { 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] = { schema: resolvedMessageSchema }\n }\n channels[channelName] = { 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 { 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 .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 input: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number(),\n }),\n output: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number(),\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(),\n description: z.string().optional(),\n inputSchema: z.object({}).passthrough().optional(),\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 })\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})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '1.0.0',\n entities: {\n modelRef: {\n schema: ModelRefSchema,\n },\n },\n events: {},\n actions: {\n generateContent: {\n input: {\n schema: ({ modelRef }) => GenerateContentInputSchema(modelRef),\n },\n output: {\n schema: () => GenerateContentOutputSchema,\n },\n },\n listModels: {\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 * as messages from '../message'\nimport { z } from '../zui'\n\nexport const hitl = new InterfaceDeclaration({\n name: 'hitl',\n version: '0.0.1',\n entities: {},\n events: {},\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 openTicket: {\n input: {\n schema: () =>\n z.object({\n userId: z.string(),\n title: z.string(),\n description: z.string().optional(),\n }),\n },\n output: {\n schema: () =>\n z.object({\n conversationId: z.string(),\n }),\n },\n },\n },\n channels: {\n ticket: {\n messages: {\n text: {\n schema: () =>\n messages.defaults.text.schema.extend({\n userId: z.string().optional().describe('Allows sending a message pretending to be a certain user'),\n }),\n },\n },\n },\n },\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", "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 configurationHeader = 'x-bp-configuration'\nexport const operationHeader = 'x-bp-operation'\nexport const typeHeader = 'x-bp-type'\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 { z } from '@bpinternal/zui'\nimport {\n botIdHeader,\n botUserIdHeader,\n configurationHeader,\n integrationIdHeader,\n operationHeader,\n webhookIdHeader,\n} from '../const'\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\nexport type IntegrationContext<Configuration = any> = {\n botId: string\n botUserId: string\n integrationId: string\n webhookId: string\n operation: IntegrationOperation\n configuration: Configuration\n}\n\nexport const extractContext = (headers: Record<string, string | undefined>): IntegrationContext => {\n const botId = headers[botIdHeader]\n const botUserId = headers[botUserIdHeader]\n const integrationId = headers[integrationIdHeader]\n const webhookId = headers[webhookIdHeader]\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 configuration: base64Configuration ? JSON.parse(Buffer.from(base64Configuration, 'base64').toString('utf-8')) : {},\n }\n}\n", "import { isApiError, Client, type Conversation, type Message, type User, RuntimeError } from '@botpress/client'\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['configuration']>\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 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(req.headers)\n\n const client = new IntegrationSpecificClient<TIntegration>(\n new Client({ botId: ctx.botId, integrationId: ctx.integrationId })\n )\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 return { status: runtimeError.code, body: JSON.stringify(runtimeError.toJSON()) }\n }\n throw thrown\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 { 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", "/* eslint-disable no-console */\nimport 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 * as client from '@botpress/client'\nimport { log } from '../log'\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 botClient = new BotSpecificClient<TBot>(new client.Client({ botId: ctx.botId }))\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) => 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) => 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) => 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.getState(x).then((y) => ({ state: { ...y.state, payload: y.state.payload } }))) as routes.GetState<TBot>\n public setState: routes.SetState<TBot> = ((x) =>\n this.client.setState(x).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,wBAAAC,EAAA,eAAAC,EAAA,yCAAAC,EAAA,oBAAAC,EAAA,cAAAC,EAAA,UAAAC,EAAA,+BAAAC,GAAA,eAAAC,GAAA,oBAAAC,IAAA,eAAAC,GAAApB,GCAA,IAAAqB,EAAA,GAAAC,EAAAD,EAAA,cAAAE,ICAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,+BAAAC,KAAA,IAAAC,EAA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,CAAO,CAC/C,EAEgB,QAAUC,GAAW,KAAK,MAAM,EAChC,MAASC,GAAmCC,EAAM,KAAK,QAASD,CAAI,CACtF",
|
|
6
|
+
"names": ["src_exports", "__export", "Bot", "BotSpecificClient", "IntegrationImplementation", "IntegrationDefinition", "IntegrationSpecificClient", "InterfaceDeclaration", "botIdHeader", "botUserIdHeader", "configurationHeader", "integrationIdHeader", "interfaces_exports", "message_exports", "operationHeader", "parseBody", "serve", "studioComponentDefinitions", "typeHeader", "webhookIdHeader", "__toCommonJS", "message_exports", "__export", "defaults", "zui_exports", "__export", "zui_default", "studioComponentDefinitions", "import_zui", "__reExport", "commonInputParams", "NonEmptyString", "textMessageSchema", "markdownMessageSchema", "imageMessageSchema", "audioMessageSchema", "videoMessageSchema", "fileMessageSchema", "locationMessageSchema", "cardSchema", "choiceSchema", "carouselSchema", "blocSchema", "blocsSchema", "defaults", "interfaces_exports", "__export", "creatable", "deletable", "hitl", "listable", "llm", "readable", "updatable", "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", "ToolCallSchema", "zui_default", "ToolChoiceSchema", "MessageSchema", "ModelRefSchema", "ModelSchema", "GenerateContentInputSchema", "modelRefSchema", "GenerateContentInputBaseSchema", "GenerateContentOutputSchema", "llm", "InterfaceDeclaration", "modelRef", "hitl", "InterfaceDeclaration", "defaults", "baseItem", "zui_default", "withId", "schema", "capitalize", "s", "camelCase", "parts", "first", "rest", "nextToken", "listable", "InterfaceDeclaration", "args", "name", "props", "creatable", "readable", "updatable", "deletable", "botIdHeader", "botUserIdHeader", "integrationIdHeader", "webhookIdHeader", "configurationHeader", "operationHeader", "typeHeader", "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", "__reExport", "src_exports", "zui_exports", "import_client", "import_zui", "integrationOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "botUserId", "botUserIdHeader", "integrationId", "integrationIdHeader", "webhookId", "webhookIdHeader", "base64Configuration", "configurationHeader", "operation", "operationHeader", "import_client", "IntegrationSpecificClient", "client", "x", "import_util", "serializeForBotMessage", "args", "util", "format", "param", "integrationLogger", "integrationHandler", "instance", "req", "ctx", "extractContext", "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", "client", "BotSpecificClient", "client", "x", "y", "import_zui", "botOperationSchema", "extractContext", "headers", "botId", "botIdHeader", "base64Configuration", "configurationHeader", "type", "typeHeader", "operation", "operationHeader", "botHandler", "instance", "req", "ctx", "extractContext", "log", "botClient", "BotSpecificClient", "props", "onEventReceived", "onRegister", "onUnregister", "onPing", "_", "client", "body", "parseBody", "event", "messagePayload", "handler", "statePayload", "eventPayload", "Bot", "props", "handler", "botHandler", "port", "serve"]
|
|
7
7
|
}
|
|
@@ -58,5 +58,9 @@ export declare class IntegrationDefinition<TConfig extends BaseConfig = BaseConf
|
|
|
58
58
|
constructor(props: IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>);
|
|
59
59
|
clone(props: Partial<IntegrationDefinitionProps<TConfig, TEvents, TActions, TChannels, TStates, TEntities>>): IntegrationDefinition<TConfig, TEvents, TActions, TChannels, TStates, TEntities>;
|
|
60
60
|
extend<E extends BaseEntities>(interfaceDeclaration: InterfaceDeclaration<E>, builder: ExtensionBuilder<TEntities, E>): this;
|
|
61
|
+
private _mergeActions;
|
|
62
|
+
private _mergeEvents;
|
|
63
|
+
private _mergeChannels;
|
|
64
|
+
private _mergeMessage;
|
|
61
65
|
}
|
|
62
66
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AnyZodObject, GenericZuiSchema, ZodRef } from '../../zui';
|
|
2
|
-
import { BaseActions, BaseEntities, BaseEvents } from './generic';
|
|
2
|
+
import { BaseActions, BaseChannels, BaseEntities, BaseEvents } from './generic';
|
|
3
3
|
import { EntityDefinition, InterfaceImplementationStatement, ResolvedInterface } from './types';
|
|
4
4
|
type EntityReferences<TEntities extends BaseEntities> = {
|
|
5
5
|
[K in keyof TEntities]: ZodRef;
|
|
@@ -7,6 +7,13 @@ type EntityReferences<TEntities extends BaseEntities> = {
|
|
|
7
7
|
type GenericEventDefinition<TEntities extends BaseEntities, TEvent extends BaseEvents[string] = BaseEvents[string]> = {
|
|
8
8
|
schema: GenericZuiSchema<EntityReferences<TEntities>, TEvent>;
|
|
9
9
|
};
|
|
10
|
+
type GenericChannelDefinition<TEntities extends BaseEntities, TChannel extends BaseChannels[string] = BaseChannels[string]> = {
|
|
11
|
+
messages: {
|
|
12
|
+
[K in keyof TChannel]: {
|
|
13
|
+
schema: GenericZuiSchema<EntityReferences<TEntities>, TChannel[K]>;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
};
|
|
10
17
|
type GenericActionDefinition<TEntities extends BaseEntities, TAction extends BaseActions[string] = BaseActions[string]> = {
|
|
11
18
|
input: {
|
|
12
19
|
schema: GenericZuiSchema<EntityReferences<TEntities>, TAction>;
|
|
@@ -18,17 +25,20 @@ type GenericActionDefinition<TEntities extends BaseEntities, TAction extends Bas
|
|
|
18
25
|
export type InterfaceTemplateNameProps<TEntities extends BaseEntities = BaseEntities> = {
|
|
19
26
|
[K in keyof TEntities]: string;
|
|
20
27
|
};
|
|
21
|
-
export type InterfaceDeclarationProps<TEntities extends BaseEntities = BaseEntities, TActions extends BaseActions = BaseActions, TEvents extends BaseEntities = BaseEntities> = {
|
|
28
|
+
export type InterfaceDeclarationProps<TEntities extends BaseEntities = BaseEntities, TActions extends BaseActions = BaseActions, TEvents extends BaseEntities = BaseEntities, TChannels extends BaseChannels = BaseChannels> = {
|
|
22
29
|
name: string;
|
|
23
30
|
version: string;
|
|
24
|
-
|
|
31
|
+
entities?: {
|
|
32
|
+
[K in keyof TEntities]: EntityDefinition<TEntities[K]>;
|
|
33
|
+
};
|
|
34
|
+
events?: {
|
|
25
35
|
[K in keyof TEvents]: GenericEventDefinition<TEntities, TEvents[K]>;
|
|
26
36
|
};
|
|
27
|
-
actions
|
|
37
|
+
actions?: {
|
|
28
38
|
[K in keyof TActions]: GenericActionDefinition<TEntities, TActions[K]>;
|
|
29
39
|
};
|
|
30
|
-
|
|
31
|
-
[K in keyof
|
|
40
|
+
channels?: {
|
|
41
|
+
[K in keyof TChannels]: GenericChannelDefinition<TEntities, TChannels[K]>;
|
|
32
42
|
};
|
|
33
43
|
templateName?: (name: string, props: InterfaceTemplateNameProps<TEntities>) => string;
|
|
34
44
|
};
|
|
@@ -48,9 +58,10 @@ export declare class InterfaceDeclaration<TEntities extends BaseEntities = BaseE
|
|
|
48
58
|
readonly props: InterfaceDeclarationProps<TEntities, TActions, TEvents>;
|
|
49
59
|
readonly name: this['props']['name'];
|
|
50
60
|
readonly version: this['props']['version'];
|
|
51
|
-
readonly entities: this['props']['entities']
|
|
52
|
-
readonly events: this['props']['events']
|
|
53
|
-
readonly actions: this['props']['actions']
|
|
61
|
+
readonly entities: NonNullable<this['props']['entities']>;
|
|
62
|
+
readonly events: NonNullable<this['props']['events']>;
|
|
63
|
+
readonly actions: NonNullable<this['props']['actions']>;
|
|
64
|
+
readonly channels: NonNullable<this['props']['channels']>;
|
|
54
65
|
readonly templateName: this['props']['templateName'];
|
|
55
66
|
constructor(props: InterfaceDeclarationProps<TEntities, TActions, TEvents>);
|
|
56
67
|
resolve(props: InterfaceResolveInput<TEntities>): InterfaceResolveOutput<TActions, TEvents>;
|
|
@@ -63,13 +63,16 @@ export type EntityDefinition<TEntity extends BaseEntities[string] = BaseEntities
|
|
|
63
63
|
title?: string;
|
|
64
64
|
description?: string;
|
|
65
65
|
};
|
|
66
|
-
export type ResolvedInterface<TEvents extends BaseEvents = BaseEvents, TActions extends BaseActions = BaseActions> = {
|
|
66
|
+
export type ResolvedInterface<TEvents extends BaseEvents = BaseEvents, TActions extends BaseActions = BaseActions, TChannels extends BaseChannels = BaseChannels> = {
|
|
67
67
|
actions: {
|
|
68
68
|
[K in keyof TActions]: ActionDefinition<TActions[K]>;
|
|
69
69
|
};
|
|
70
70
|
events: {
|
|
71
71
|
[K in keyof TEvents]: EventDefinition<TEvents[K]>;
|
|
72
72
|
};
|
|
73
|
+
channels: {
|
|
74
|
+
[K in keyof TChannels]: ChannelDefinition<TChannels[K]>;
|
|
75
|
+
};
|
|
73
76
|
};
|
|
74
77
|
export type InterfaceImplementationStatement = {
|
|
75
78
|
name: string;
|
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
import { InterfaceDeclaration } from '../integration/definition';
|
|
2
2
|
export declare const hitl: InterfaceDeclaration<import("../integration/definition/generic").BaseEntities, {
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
createUser: import("@bpinternal/zui").ZodObject<{
|
|
4
|
+
name: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
5
|
+
pictureUrl: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
6
|
+
email: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
5
7
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
6
|
-
|
|
8
|
+
name?: string | undefined;
|
|
9
|
+
pictureUrl?: string | undefined;
|
|
10
|
+
email?: string | undefined;
|
|
7
11
|
}, {
|
|
8
|
-
|
|
12
|
+
name?: string | undefined;
|
|
13
|
+
pictureUrl?: string | undefined;
|
|
14
|
+
email?: string | undefined;
|
|
15
|
+
}>;
|
|
16
|
+
openTicket: import("@bpinternal/zui").ZodObject<{
|
|
17
|
+
userId: import("@bpinternal/zui").ZodString;
|
|
18
|
+
title: import("@bpinternal/zui").ZodString;
|
|
19
|
+
description: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
20
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
21
|
+
title: string;
|
|
22
|
+
userId: string;
|
|
23
|
+
description?: string | undefined;
|
|
24
|
+
}, {
|
|
25
|
+
title: string;
|
|
26
|
+
userId: string;
|
|
27
|
+
description?: string | undefined;
|
|
9
28
|
}>;
|
|
10
29
|
}, import("../integration/definition/generic").BaseEvents>;
|
package/dist/interfaces/llm.d.ts
CHANGED
|
@@ -113,14 +113,60 @@ declare const MessageSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
113
113
|
mimeType?: string | undefined;
|
|
114
114
|
}[] | undefined;
|
|
115
115
|
}>;
|
|
116
|
+
declare const ModelSchema: import("@bpinternal/zui").ZodObject<{
|
|
117
|
+
id: import("@bpinternal/zui").ZodString;
|
|
118
|
+
name: import("@bpinternal/zui").ZodString;
|
|
119
|
+
input: import("@bpinternal/zui").ZodObject<{
|
|
120
|
+
maxTokens: import("@bpinternal/zui").ZodNumber;
|
|
121
|
+
costPer1MTokens: import("@bpinternal/zui").ZodNumber;
|
|
122
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
123
|
+
maxTokens: number;
|
|
124
|
+
costPer1MTokens: number;
|
|
125
|
+
}, {
|
|
126
|
+
maxTokens: number;
|
|
127
|
+
costPer1MTokens: number;
|
|
128
|
+
}>;
|
|
129
|
+
output: import("@bpinternal/zui").ZodObject<{
|
|
130
|
+
maxTokens: import("@bpinternal/zui").ZodNumber;
|
|
131
|
+
costPer1MTokens: import("@bpinternal/zui").ZodNumber;
|
|
132
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
133
|
+
maxTokens: number;
|
|
134
|
+
costPer1MTokens: number;
|
|
135
|
+
}, {
|
|
136
|
+
maxTokens: number;
|
|
137
|
+
costPer1MTokens: number;
|
|
138
|
+
}>;
|
|
139
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
140
|
+
id: string;
|
|
141
|
+
name: string;
|
|
142
|
+
input: {
|
|
143
|
+
maxTokens: number;
|
|
144
|
+
costPer1MTokens: number;
|
|
145
|
+
};
|
|
146
|
+
output: {
|
|
147
|
+
maxTokens: number;
|
|
148
|
+
costPer1MTokens: number;
|
|
149
|
+
};
|
|
150
|
+
}, {
|
|
151
|
+
id: string;
|
|
152
|
+
name: string;
|
|
153
|
+
input: {
|
|
154
|
+
maxTokens: number;
|
|
155
|
+
costPer1MTokens: number;
|
|
156
|
+
};
|
|
157
|
+
output: {
|
|
158
|
+
maxTokens: number;
|
|
159
|
+
costPer1MTokens: number;
|
|
160
|
+
};
|
|
161
|
+
}>;
|
|
116
162
|
declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObject<{
|
|
117
|
-
model: import("@bpinternal/zui").ZodObject<{
|
|
163
|
+
model: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{
|
|
118
164
|
id: import("@bpinternal/zui").ZodString;
|
|
119
165
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
120
166
|
id: string;
|
|
121
167
|
}, {
|
|
122
168
|
id: string;
|
|
123
|
-
}
|
|
169
|
+
}>>;
|
|
124
170
|
systemPrompt: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
125
171
|
messages: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
126
172
|
role: import("@bpinternal/zui").ZodEnum<["user", "assistant"]>;
|
|
@@ -254,9 +300,6 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
254
300
|
}>>;
|
|
255
301
|
userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
256
302
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
257
|
-
model: {
|
|
258
|
-
id: string;
|
|
259
|
-
};
|
|
260
303
|
messages: {
|
|
261
304
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
262
305
|
role: "user" | "assistant";
|
|
@@ -278,9 +321,12 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
278
321
|
}[];
|
|
279
322
|
temperature: number;
|
|
280
323
|
topP: number;
|
|
324
|
+
maxTokens?: number | undefined;
|
|
325
|
+
model?: {
|
|
326
|
+
id: string;
|
|
327
|
+
} | undefined;
|
|
281
328
|
systemPrompt?: string | undefined;
|
|
282
329
|
responseFormat?: "text" | "json_object" | undefined;
|
|
283
|
-
maxTokens?: number | undefined;
|
|
284
330
|
stopSequences?: string[] | undefined;
|
|
285
331
|
tools?: {
|
|
286
332
|
function: {
|
|
@@ -296,9 +342,6 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
296
342
|
} | undefined;
|
|
297
343
|
userId?: string | undefined;
|
|
298
344
|
}, {
|
|
299
|
-
model: {
|
|
300
|
-
id: string;
|
|
301
|
-
};
|
|
302
345
|
messages: {
|
|
303
346
|
role: "user" | "assistant";
|
|
304
347
|
type?: "text" | "tool_calls" | "tool_result" | "multipart" | undefined;
|
|
@@ -318,9 +361,12 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
318
361
|
mimeType?: string | undefined;
|
|
319
362
|
}[] | undefined;
|
|
320
363
|
}[];
|
|
364
|
+
maxTokens?: number | undefined;
|
|
365
|
+
model?: {
|
|
366
|
+
id: string;
|
|
367
|
+
} | undefined;
|
|
321
368
|
systemPrompt?: string | undefined;
|
|
322
369
|
responseFormat?: "text" | "json_object" | undefined;
|
|
323
|
-
maxTokens?: number | undefined;
|
|
324
370
|
temperature?: number | undefined;
|
|
325
371
|
topP?: number | undefined;
|
|
326
372
|
stopSequences?: string[] | undefined;
|
|
@@ -513,7 +559,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
513
559
|
};
|
|
514
560
|
}>;
|
|
515
561
|
export declare const llm: InterfaceDeclaration<{
|
|
516
|
-
|
|
562
|
+
modelRef: import("@bpinternal/zui").ZodObject<{
|
|
517
563
|
id: import("@bpinternal/zui").ZodString;
|
|
518
564
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
519
565
|
id: string;
|
|
@@ -522,7 +568,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
522
568
|
}>;
|
|
523
569
|
}, {
|
|
524
570
|
generateContent: import("@bpinternal/zui").ZodObject<{
|
|
525
|
-
model: import("@bpinternal/zui").ZodRef
|
|
571
|
+
model: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodRef>;
|
|
526
572
|
systemPrompt: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
527
573
|
messages: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
528
574
|
role: import("@bpinternal/zui").ZodEnum<["user", "assistant"]>;
|
|
@@ -656,7 +702,6 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
656
702
|
}>>;
|
|
657
703
|
userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
658
704
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
659
|
-
model: {};
|
|
660
705
|
messages: {
|
|
661
706
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
662
707
|
role: "user" | "assistant";
|
|
@@ -678,9 +723,10 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
678
723
|
}[];
|
|
679
724
|
temperature: number;
|
|
680
725
|
topP: number;
|
|
726
|
+
maxTokens?: number | undefined;
|
|
727
|
+
model?: {} | undefined;
|
|
681
728
|
systemPrompt?: string | undefined;
|
|
682
729
|
responseFormat?: "text" | "json_object" | undefined;
|
|
683
|
-
maxTokens?: number | undefined;
|
|
684
730
|
stopSequences?: string[] | undefined;
|
|
685
731
|
tools?: {
|
|
686
732
|
function: {
|
|
@@ -696,7 +742,6 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
696
742
|
} | undefined;
|
|
697
743
|
userId?: string | undefined;
|
|
698
744
|
}, {
|
|
699
|
-
model: {};
|
|
700
745
|
messages: {
|
|
701
746
|
role: "user" | "assistant";
|
|
702
747
|
type?: "text" | "tool_calls" | "tool_result" | "multipart" | undefined;
|
|
@@ -716,9 +761,10 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
716
761
|
mimeType?: string | undefined;
|
|
717
762
|
}[] | undefined;
|
|
718
763
|
}[];
|
|
764
|
+
maxTokens?: number | undefined;
|
|
765
|
+
model?: {} | undefined;
|
|
719
766
|
systemPrompt?: string | undefined;
|
|
720
767
|
responseFormat?: "text" | "json_object" | undefined;
|
|
721
|
-
maxTokens?: number | undefined;
|
|
722
768
|
temperature?: number | undefined;
|
|
723
769
|
topP?: number | undefined;
|
|
724
770
|
stopSequences?: string[] | undefined;
|
|
@@ -736,11 +782,14 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
736
782
|
} | undefined;
|
|
737
783
|
userId?: string | undefined;
|
|
738
784
|
}>;
|
|
785
|
+
listModels: import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>;
|
|
739
786
|
}, import("../integration/definition/generic").BaseEvents>;
|
|
740
787
|
export declare namespace llm {
|
|
741
788
|
type GenerateContentInput = z.infer<typeof GenerateContentInputBaseSchema>;
|
|
742
789
|
type GenerateContentOutput = z.infer<typeof GenerateContentOutputSchema>;
|
|
743
790
|
type ToolCall = z.infer<typeof ToolCallSchema>;
|
|
744
791
|
type Message = z.infer<typeof MessageSchema>;
|
|
792
|
+
type Model = z.infer<typeof ModelSchema>;
|
|
793
|
+
type ModelDetails = Omit<Model, 'id'>;
|
|
745
794
|
}
|
|
746
795
|
export {};
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export declare const unique: <T>(array: T[]) => T[];
|
|
1
2
|
export declare const pairs: <K extends string, V>(obj: Record<K, V>) => [K, V][];
|
|
2
3
|
export declare const values: <K extends string, V>(obj: Record<K, V>) => V[];
|
|
3
4
|
export declare const mapValues: <K extends string, V, R>(obj: Record<K, V>, fn: (value: V, key: K) => R) => Record<K, R>;
|
|
5
|
+
export declare const mergeRecords: <K extends string, V>(a: Record<K, V>, b: Record<K, V>, merge: (v1: V, v2: V) => V) => Record<K, V>;
|