@botpress/sdk 0.8.37 → 0.8.39
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
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
|
|
2
|
-
> @botpress/sdk@0.8.
|
|
2
|
+
> @botpress/sdk@0.8.39 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.39 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.39 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 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});
|
|
1
|
+
"use strict";var Ae=Object.create;var H=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var G=(t,e)=>{for(var n in e)H(t,n,{get:e[n],enumerable:!0})},F=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ue(e))!De.call(t,s)&&s!==n&&H(t,s,{get:()=>e[s],enumerable:!(a=Re(e,s))||a.enumerable});return t},m=(t,e,n)=>(F(t,e,"default"),n&&F(n,e,"default")),ne=(t,e,n)=>(n=t!=null?Ae(ke(t)):{},F(e||!t||!t.__esModule?H(n,"default",{value:t,enumerable:!0}):n,t)),Oe=t=>F(H({},"__esModule",{value:!0}),t);var I={};G(I,{Bot:()=>_,BotSpecificClient:()=>A,Integration:()=>K,IntegrationDefinition:()=>C,IntegrationSpecificClient:()=>M,InterfaceDeclaration:()=>T,RuntimeError:()=>z.RuntimeError,botIdHeader:()=>k,botUserIdHeader:()=>Q,configurationHeader:()=>D,integrationIdHeader:()=>X,interfaces:()=>J,isApiError:()=>z.isApiError,messages:()=>Z,operationHeader:()=>O,parseBody:()=>b,serve:()=>j,studioComponentDefinitions:()=>oe,typeHeader:()=>ee,webhookIdHeader:()=>Y});module.exports=Oe(I);var Z={};G(Z,{defaults:()=>Ge});var r={};G(r,{default:()=>o,studioComponentDefinitions:()=>oe});var c=require("@bpinternal/zui");m(r,require("@bpinternal/zui"));var y=c.z.object({allowDynamicVariable:c.z.boolean().optional(),horizontal:c.z.boolean().optional()}),oe={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:{}},o=c.z;var h=r.z.string().min(1),ie=r.z.object({text:h}),ae=r.z.object({markdown:h}),re=r.z.object({imageUrl:h}),ce=r.z.object({audioUrl:h}),le=r.z.object({videoUrl:h}),pe=r.z.object({fileUrl:h,title:h.optional()}),ge=r.z.object({latitude:r.z.number(),longitude:r.z.number(),address:r.z.string().optional(),title:r.z.string().optional()}),de=r.z.object({title:h,subtitle:h.optional(),imageUrl:h.optional(),actions:r.z.array(r.z.object({action:r.z.enum(["postback","url","say"]),label:h,value:h}))}),se=r.z.object({text:h,options:r.z.array(r.z.object({label:h,value:h}))}),je=r.z.object({items:r.z.array(de)}),Fe=r.z.discriminatedUnion("type",[r.z.object({type:r.z.literal("text"),payload:ie}),r.z.object({type:r.z.literal("markdown"),payload:ae}),r.z.object({type:r.z.literal("image"),payload:re}),r.z.object({type:r.z.literal("audio"),payload:ce}),r.z.object({type:r.z.literal("video"),payload:le}),r.z.object({type:r.z.literal("file"),payload:pe}),r.z.object({type:r.z.literal("location"),payload:ge})]),He=r.z.object({items:r.z.array(Fe)}),Ge={text:{schema:ie},markdown:{schema:ae},image:{schema:re},audio:{schema:ce},video:{schema:le},file:{schema:pe},location:{schema:ge},carousel:{schema:je},card:{schema:de},dropdown:{schema:se},choice:{schema:se},bloc:{schema:He}};var J={};G(J,{creatable:()=>Qe,deletable:()=>et,listable:()=>Je,llm:()=>Ze,readable:()=>Xe,textToImage:()=>$e,updatable:()=>Ye});var Ne=t=>Array.from(new Set(t)),B=t=>Object.entries(t);var S=(t,e)=>Object.fromEntries(B(t).map(([n,a])=>[n,e(a,n)])),R=(t,e,n)=>{let a=Ne([...Object.keys(t),...Object.keys(e)]),s={};for(let i of a){let l=t[i],g=e[i];l&&g?s[i]=n(l,g):l?s[i]=l:g&&(s[i]=g)}return s};var V=Symbol("schemaName"),me=t=>t?S(t,(n,a)=>({...n,[V]:a})):{},ue=t=>t[V]!==void 0,he=t=>t[V];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(me(this.entities)),s=B(a).find(([u,x])=>!ue(x));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 i=S(a,u=>({name:he(u),schema:u.schema})),{resolved:l,implementStatement:g}=e.resolve({entities:i}),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(i).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 a=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:a}};_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,a={name:this.name,version:this.version,entities:S(n,p=>({name:p.name})),actions:{},events:{}},s={},i={},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);s[x]={input:{schema:f},output:{schema:u}},a.actions[p]={name:x}}for(let[p,d]of B(this.events)){let f=this._dereference(d.schema,n),u=this._rename(n,p);i[u]={schema:f},a.events[p]={name:u}}for(let[p,d]of B(this.channels)){let f={};for(let[u,x]of B(d.messages)){let L=this._dereference(x.schema,n);f[u]={schema:L}}l[p]={messages:f}}return{resolved:{actions:s,events:i,channels:l},implementStatement:a}}_dereference(e,n){let a={},s={};for(let[i,l]of B(n))a[i]=l.schema,s[i]=o.ref(i);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 Ke=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.")})}),_e=o.object({type:o.enum(["auto","specific","any","none",""]).optional(),functionName:o.string().optional().describe('Required if `type` is "specific"')}),Te=o.object({role:o.enum(["user","assistant"]),type:o.enum(["text","tool_calls","tool_result","multipart"]).default("text"),toolCalls:o.array(Ke).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().nullable().describe('Required unless `type` is "tool_call". If `type` is "multipart", this field must be an array of content objects. If `type` is "tool_result" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is "tool_call" then the `toolCalls` field should be used instead.')}),$=o.object({id:o.string()}),ze=$.extend({name:o.string(),input:o.object({maxTokens:o.number().int(),costPer1MTokens:o.number().describe("Cost per 1 million tokens, in U.S. dollars")}),output:o.object({maxTokens:o.number().int(),costPer1MTokens:o.number().describe("Cost per 1 million tokens, in U.S. dollars")})}),fe=t=>o.object({model:t.describe("Model to use for content generation").optional(),systemPrompt:o.string().optional().describe("Optional system prompt to guide the model"),messages:o.array(Te).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().describe("Function name"),description:o.string().optional(),argumentsSchema:o.object({}).passthrough().optional().describe("JSON schema of the function arguments")})})).optional(),toolChoice:_e.optional(),userId:o.string().optional(),debug:o.boolean().optional().describe("Set to `true` to output debug information to the bot logs")}),Ht=fe($),Le=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(Te.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")})}),Ze=new T({name:"llm",version:"3.1.0",entities:{modelRef:{schema:$}},events:{},actions:{generateContent:{input:{schema:({modelRef:t})=>fe(t)},output:{schema:()=>Le}},listLanguageModels:{input:{schema:()=>o.object({})},output:{schema:({modelRef:t})=>o.object({models:o.array(o.intersection(ze,t))})}}}});var W=o.object({id:o.string()}),qe=W.extend({name:o.string(),costPerImage:o.number().describe("Cost per image generation, in U.S. dollars"),sizes:o.array(o.string()).describe("Available image sizes"),defaultSize:o.string().describe("Default image size generated by model")}),ye=o.object({}).describe("Model-specific parameters for image generation"),be=(t,e)=>o.object({model:t.optional().describe("Model to use for image generation"),prompt:o.string(),size:o.string().optional(),params:e.optional()}),_t=be(W,ye),Ve=o.object({model:o.string().describe("Model name used"),imageUrl:o.string().describe("Temporary URL of generated image"),cost:o.number().describe("Cost of the image generation, in U.S. dollars")}),$e=new T({name:"textToImage",version:"1.0.0",entities:{imageModelRef:{schema:W},imageGenerationParams:{schema:ye}},actions:{generateImage:{input:{schema:({imageModelRef:t,imageGenerationParams:e})=>be(t,e)},output:{schema:()=>Ve}},listImageModels:{input:{schema:()=>o.object({})},output:{schema:({imageModelRef:t})=>o.object({models:o.array(o.intersection(qe,t))})}}}});var v=o.object({id:o.string()}),E=t=>o.intersection(t,v),We=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(We)].join(""):""},Ie=o.string().optional(),Je=new T({name:"listable",version:"0.0.1",entities:{item:{schema:v}},events:{},actions:{list:{input:{schema:()=>o.object({nextToken:Ie})},output:{schema:t=>o.object({items:o.array(E(t.item)),meta:o.object({nextToken:Ie})})}}},templateName:(t,e)=>U(e.item,t)}),Qe=new T({name:"creatable",version:"0.0.1",entities:{item:{schema:v}},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)}),Xe=new T({name:"readable",version:"0.0.1",entities:{item:{schema:v}},events:{},actions:{read:{input:{schema:()=>v},output:{schema:t=>o.object({item:E(t.item)})}}},templateName:(t,e)=>U(e.item,t)}),Ye=new T({name:"updatable",version:"0.0.1",entities:{item:{schema:v}},events:{updated:{schema:t=>o.object({item:E(t.item)})}},actions:{update:{input:{schema:t=>v.extend({item:t.item})},output:{schema:t=>o.object({item:E(t.item)})}}},templateName:(t,e)=>U(e.item,t)}),et=new T({name:"deletable",version:"0.0.1",entities:{item:{schema:v}},events:{deleted:{schema:()=>v}},actions:{delete:{input:{schema:()=>v},output:{schema:()=>o.object({})}}},templateName:(t,e)=>U(e.item,t)});var k="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 ve=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=st){let a=(0,ve.createServer)(async(s,i)=>{try{let l=await tt(s);if(l.path==="/health"){i.writeHead(200).end("ok");return}let g=await t(l);i.writeHead(g?.status??200,g?.headers??{}).end(g?.body??"{}")}catch(l){P.error("Error while handling request",{error:l?.message??"Internal error occured"}),i.writeHead(500).end(JSON.stringify({error:l?.message??"Internal error occured"}))}});return a.listen(e,()=>n(e)),a}async function tt(t){let e=await ot(t),n={};for(let s=0;s<t.rawHeaders.length;s+=2){let i=t.rawHeaders[s].toLowerCase(),l=t.rawHeaders[s+1];n[i]=l}let a=new URL(t.url??"",t.headers.host?`http://${t.headers.host}`:"http://botpress.cloud");return{body:e,path:a.pathname,query:nt(a.search,"?"),headers:n,method:t.method?.toUpperCase()??"GET"}}function nt(t,e){return t.indexOf(e)===0?t.slice(e.length):t}async function ot(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 st(t){P.info(`Listening on port ${t}`)}m(I,r,module.exports);var z=require("@botpress/client");var Be=require("@bpinternal/zui");var it=Be.z.enum(["webhook_received","message_created","action_triggered","register","unregister","ping","create_user","create_conversation"]),xe=t=>{let e=t[k],n=t[Q],a=t[X],s=t[Y],i=t[D],l=it.parse(t[O]);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(!i)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:i?JSON.parse(Buffer.from(i,"base64").toString("utf-8")):{}}};var w=require("@botpress/client");var M=class{constructor(e){this.client=e}createConversation=e=>this.client.createConversation(e);getConversation=e=>this.client.getConversation(e);listConversations=e=>this.client.listConversations(e);getOrCreateConversation=e=>this.client.getOrCreateConversation(e);updateConversation=e=>this.client.updateConversation(e);deleteConversation=e=>this.client.deleteConversation(e);listParticipants=e=>this.client.listParticipants(e);addParticipant=e=>this.client.addParticipant(e);getParticipant=e=>this.client.getParticipant(e);removeParticipant=e=>this.client.removeParticipant(e);createEvent=e=>this.client.createEvent(e);getEvent=e=>this.client.getEvent(e);listEvents=e=>this.client.listEvents(e);createMessage=e=>this.client.createMessage(e);getOrCreateMessage=e=>this.client.getOrCreateMessage(e);getMessage=e=>this.client.getMessage(e);updateMessage=e=>this.client.updateMessage(e);listMessages=e=>this.client.listMessages(e);deleteMessage=e=>this.client.deleteMessage(e);createUser=e=>this.client.createUser(e);getUser=e=>this.client.getUser(e);listUsers=e=>this.client.listUsers(e);getOrCreateUser=e=>this.client.getOrCreateUser(e);updateUser=e=>this.client.updateUser(e);deleteUser=e=>this.client.deleteUser(e);getState=e=>this.client.getState(e);setState=e=>this.client.setState(e);getOrSetState=e=>this.client.getOrSetState(e);patchState=e=>this.client.patchState(e);configureIntegration=e=>this.client.configureIntegration(e);uploadFile=e=>this.client.uploadFile(e);upsertFile=e=>this.client.upsertFile(e);deleteFile=e=>this.client.deleteFile(e);listFiles=e=>this.client.listFiles(e);getFile=e=>this.client.getFile(e);updateFileMetadata=e=>this.client.updateFileMetadata(e)};var te=ne(require("util")),N=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)}},Se={forBot:()=>({info:(...t)=>{console.info(N(t))},warn:(...t)=>{console.warn(N(t))},error:(...t)=>{console.error(N(t))},debug:(...t)=>{console.debug(N(t))}})};var Ce=t=>async e=>{let n=xe(e.headers),a=new M(new w.Client({botId:n.botId,integrationId:n.integrationId})),s={ctx:n,req:e,client:a,logger:Se,instance:t};try{let i;switch(n.operation){case"webhook_received":i=await rt(s);break;case"register":i=await ct(s);break;case"unregister":i=await lt(s);break;case"message_created":i=await dt(s);break;case"action_triggered":i=await mt(s);break;case"ping":i=await at(s);break;case"create_user":i=await pt(s);break;case"create_conversation":i=await gt(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return i?{...i,status:i.status??200}:{status:200}}catch(i){if((0,w.isApiError)(i)){let l=new w.RuntimeError(i.message,i);return{status:l.code,body:JSON.stringify(l.toJSON())}}throw i}},at=async t=>{},rt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{let{req:i}=b(n);return s.webhook({client:t,ctx:e,req:i,logger:a})},ct=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.register)return;let{webhookUrl:i}=b(n);await s.register({client:t,ctx:e,webhookUrl:i,logger:a})},lt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.unregister)return;let{webhookUrl:i}=b(n);await s.unregister({ctx:e,webhookUrl:i,client:t,logger:a})},pt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createUser)return;let{tags:i}=b(n);return await s.createUser({ctx:e,client:t,tags:i,logger:a})},gt=async({client:t,ctx:e,req:n,logger:a,instance:s})=>{if(!s.createConversation)return;let{channel:i,tags:l}=b(n);return await s.createConversation({ctx:e,client:t,channel:i,tags:l,logger:a})},dt=async({ctx:t,req:e,client:n,logger:a,instance:s})=>{let{conversation:i,user:l,type:g,payload:p,message:d}=b(e),f=s.channels[i.channel];if(!f)throw new Error(`Channel ${i.channel} not found`);let u=f.messages[g];if(!u)throw new Error(`Message of type ${g} not found in channel ${i.channel}`);await u({ctx:t,conversation:i,message:d,user:l,type:g,client:n,payload:p,ack:async({tags:L})=>{await n.updateMessage({id:d.id,tags:L})},logger:a})},mt=async({req:t,ctx:e,client:n,logger:a,instance:s})=>{let{input:i,type:l}=b(t);if(!l)throw new Error("Missing action type");let g=s.actions[l];if(!g)throw new Error(`Action ${l} not found`);let p=await g({ctx:e,input:i,client:n,type:l,logger:a});return{body:JSON.stringify({output:p})}};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=Ce(this);start=e=>j(this.handler,e)};var Me=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 Ee=require("@bpinternal/zui");var ut=Ee.z.enum(["event_received","register","unregister","ping","action_triggered"]),Pe=t=>{let e=t[k],n=t[D],a=t[ee],s=ut.parse(t[O]);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 we=t=>async e=>{let n=Pe(e.headers);n.operation!=="ping"&&P.info(`Received ${n.operation} operation for bot ${n.botId} of type ${n.type}`);let a=new A(new Me.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 yt(s);break;case"register":await Tt(s);break;case"unregister":await ft(s);break;case"ping":await ht(s);break;default:throw new Error(`Unknown operation ${n.operation}`)}return{status:200}},ht=async t=>{},Tt=async t=>{},ft=async t=>{},yt=async({ctx:t,req:e,client:n,instance:a})=>{P.debug(`Received event ${t.type}`);let s=b(e),i=s.event;switch(t.type){case"message_created":let l={user:i.payload.user,conversation:i.payload.conversation,message:i.payload.message,states:i.payload.states,event:i};await Promise.all(a.messageHandlers.map(d=>d({client:n,ctx:t,...l})));break;case"state_expired":let g={state:i.payload.state};await Promise.all(a.stateExpiredHandlers.map(d=>d({client:n,ctx:t,...g})));break;default:let p={event:s.event};await Promise.all(a.eventHandlers.map(d=>d({client:n,ctx:t,...p})))}};var _=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=we(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
|
-
"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/
|
|
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,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,QAAQ,EAAE,SAAS,EAChC,eAAgB,IAAE,QAAQ,EAAE,SAAS,EACrC,YAAa,IAAE,MAAM,IAAE,OAAO,CAAC,EAAE,SAAS,CAC5C,CAAC,CACH,EACA,SAAU,CACR,GAAI,WACJ,OAAQA,EAAkB,OAAO,CAC/B,WAAY,IAAE,QAAQ,EAAE,SAAS,CACnC,CAAC,CACH,EACA,WAAY,CACV,GAAI,aACJ,OAAQA,EAAkB,OAAO,CAAC,CAAC,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,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", "
|
|
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/text-to-image.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 './text-to-image'\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 .nullable()\n .describe(\n 'Required unless `type` is \"tool_call\". If `type` is \"multipart\", this field must be an array of content objects. If `type` is \"tool_result\" then this field should be the result of the tool call (a plain string or a JSON-encoded array or object). If `type` is \"tool_call\" then the `toolCalls` field should be used instead.'\n ),\n})\n\nconst ModelRefSchema = z.object({ id: z.string() })\n\nconst ModelSchema = ModelRefSchema.extend({\n name: z.string(),\n input: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n output: z.object({\n maxTokens: z.number().int(),\n costPer1MTokens: z.number().describe('Cost per 1 million tokens, in U.S. dollars'),\n }),\n})\n\nconst GenerateContentInputSchema = <S extends z.ZodSchema>(modelRefSchema: S) =>\n z.object({\n model: modelRefSchema.describe('Model to use for content generation').optional(),\n systemPrompt: z.string().optional().describe('Optional system prompt to guide the model'),\n messages: z.array(MessageSchema).describe('Array of messages for the model to process'),\n responseFormat: z\n .enum(['text', 'json_object'])\n .optional()\n .describe(\n 'Response format expected from the model. If \"json_object\" is chosen, you must instruct the model to generate JSON either via the system prompt or a user message.'\n ), // note: only OpenAI and Groq support this but for other models we can just append this as an indication in the system prompt\n // note: we don't support streaming yet\n maxTokens: z.number().optional().describe('Maximum number of tokens allowed in the generated response'),\n temperature: z\n .number()\n .min(0)\n .max(2)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .default(1)\n .describe('Sampling temperature for the model. Higher values result in more random outputs.'),\n topP: z\n .number()\n .min(0)\n .max(1)\n .default(1)\n // @ts-ignore\n .displayAs({ id: 'slider', params: { stepSize: 0.01, horizontal: true } })\n .describe(\n 'Top-p sampling parameter. Limits sampling to the smallest set of tokens with a cumulative probability above the threshold.'\n ), // TODO: .placeholder() from zui doesn't work, so we have to use .default() which introduces some typing issues\n // note: topK is supported by Claude and Gemini but not by OpenAI or Groq\n stopSequences: z\n .array(z.string())\n .max(4)\n .optional()\n .describe('Sequences where the model should stop generating further tokens.'),\n tools: z\n .array(\n z.object({\n type: z.literal('function'),\n function: z.object({\n name: z.string().describe('Function name'),\n description: z.string().optional(),\n argumentsSchema: z.object({}).passthrough().optional().describe('JSON schema of the function arguments'),\n }),\n })\n )\n .optional(),\n // TODO: an object with options doesn't seem to be supported by the Studio as it's not rendering correctly, the dropdown for \"type\" is not working and it's sending a blank value instead which causes a schema validation error unless an empty value is allowed in the `type` enum\n toolChoice: ToolChoiceSchema.optional(), // note: Gemini doesn't support this but we can just ignore it there\n userId: z.string().optional(),\n debug: z.boolean().optional().describe('Set to `true` to output debug information to the bot logs'),\n })\n\nconst GenerateContentInputBaseSchema = GenerateContentInputSchema(ModelRefSchema)\n\nconst GenerateContentOutputSchema = z.object({\n id: z.string().describe('Response ID from LLM provider'),\n provider: z.string().describe('LLM provider name'),\n model: z.string().describe('Model name'),\n choices: z.array(\n MessageSchema.omit({ role: true }).extend({\n role: z.literal('assistant'),\n index: z.number().int(),\n stopReason: z.enum(['stop', 'max_tokens', 'tool_calls', 'content_filter', 'other']),\n // note: stopSequence is supported by Claude but not by OpenAI, Groq or Gemini\n })\n ),\n usage: z.object({\n inputTokens: z.number().int().describe('Number of input tokens used by the model'),\n inputCost: z.number().describe('Cost of the input tokens received by the model, in U.S. dollars'),\n outputTokens: z.number().int().describe('Number of output tokens used by the model'),\n outputCost: z.number().describe('Cost of the output tokens generated by the model, in U.S. dollars'),\n }),\n})\n\nexport const llm = new InterfaceDeclaration({\n name: 'llm',\n version: '3.1.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 listLanguageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ modelRef }) =>\n z.object({\n models: z.array(z.intersection(ModelSchema, modelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace llm {\n export type GenerateContentInput = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateContentOutput = z.infer<typeof GenerateContentOutputSchema>\n export type ToolCall = z.infer<typeof ToolCallSchema>\n export type Message = z.infer<typeof MessageSchema>\n export type Model = z.infer<typeof ModelSchema>\n export type ModelDetails = Omit<Model, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/definition'\nimport z from '../zui'\n\nconst ImageModelRefSchema = z.object({\n id: z.string(),\n})\n\nconst ImageModelSchema = ImageModelRefSchema.extend({\n name: z.string(),\n costPerImage: z.number().describe('Cost per image generation, in U.S. dollars'),\n sizes: z.array(z.string()).describe('Available image sizes'),\n defaultSize: z.string().describe('Default image size generated by model'),\n})\n\nconst ImageGenerationParamsSchema = z.object({}).describe('Model-specific parameters for image generation')\n\nconst GenerateImageInputSchema = <TModelRef extends z.ZodSchema, TParams extends z.ZodSchema>(\n imageModelRefSchema: TModelRef,\n paramsSchema: TParams\n) =>\n z.object({\n model: imageModelRefSchema.optional().describe('Model to use for image generation'),\n prompt: z.string(),\n size: z.string().optional(),\n params: paramsSchema.optional(),\n })\n\nconst GenerateContentInputBaseSchema = GenerateImageInputSchema(ImageModelRefSchema, ImageGenerationParamsSchema)\n\nconst GenerateImageOutputSchema = z.object({\n model: z.string().describe('Model name used'),\n imageUrl: z.string().describe('Temporary URL of generated image'),\n cost: z.number().describe('Cost of the image generation, in U.S. dollars'),\n})\n\nexport const textToImage = new InterfaceDeclaration({\n name: 'textToImage',\n version: '1.0.0',\n entities: {\n imageModelRef: {\n schema: ImageModelRefSchema,\n },\n imageGenerationParams: {\n schema: ImageGenerationParamsSchema,\n },\n },\n actions: {\n generateImage: {\n input: {\n schema: ({ imageModelRef, imageGenerationParams }) =>\n GenerateImageInputSchema(imageModelRef, imageGenerationParams),\n },\n output: {\n schema: () => GenerateImageOutputSchema,\n },\n },\n listImageModels: {\n input: {\n schema: () => z.object({}),\n },\n output: {\n schema: ({ imageModelRef }) =>\n z.object({\n models: z.array(z.intersection(ImageModelSchema, imageModelRef)),\n }),\n },\n },\n },\n})\n\nexport namespace textToImage {\n export type GenerateImageInputSchema = z.infer<typeof GenerateContentInputBaseSchema>\n export type GenerateImageOutputSchema = z.infer<typeof GenerateImageOutputSchema>\n export type ImageModel = z.infer<typeof ImageModelSchema>\n export type ImageModelDetails = Omit<ImageModel, 'id'>\n}\n", "import { InterfaceDeclaration } from '../integration/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,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,QAAQ,EAAE,SAAS,EAChC,eAAgB,IAAE,QAAQ,EAA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L,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", "listable", "llm", "readable", "textToImage", "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", "ImageModelRefSchema", "zui_default", "ImageModelSchema", "ImageGenerationParamsSchema", "GenerateImageInputSchema", "imageModelRefSchema", "paramsSchema", "GenerateContentInputBaseSchema", "GenerateImageOutputSchema", "textToImage", "InterfaceDeclaration", "imageModelRef", "imageGenerationParams", "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", "i", "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
|
}
|
package/dist/interfaces/llm.d.ts
CHANGED
|
@@ -60,7 +60,7 @@ declare const MessageSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
60
60
|
id: string;
|
|
61
61
|
}>, "many">>;
|
|
62
62
|
toolResultCallId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
63
|
-
content: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
63
|
+
content: import("@bpinternal/zui").ZodNullable<import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
64
64
|
type: import("@bpinternal/zui").ZodEnum<["text", "image"]>;
|
|
65
65
|
mimeType: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
66
66
|
text: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
@@ -75,7 +75,7 @@ declare const MessageSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
75
75
|
text?: string | undefined;
|
|
76
76
|
url?: string | undefined;
|
|
77
77
|
mimeType?: string | undefined;
|
|
78
|
-
}>, "many">]
|
|
78
|
+
}>, "many">]>>>;
|
|
79
79
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
80
80
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
81
81
|
role: "user" | "assistant";
|
|
@@ -93,7 +93,7 @@ declare const MessageSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
93
93
|
text?: string | undefined;
|
|
94
94
|
url?: string | undefined;
|
|
95
95
|
mimeType?: string | undefined;
|
|
96
|
-
}[] | undefined;
|
|
96
|
+
}[] | null | undefined;
|
|
97
97
|
}, {
|
|
98
98
|
role: "user" | "assistant";
|
|
99
99
|
type?: "text" | "tool_calls" | "tool_result" | "multipart" | undefined;
|
|
@@ -111,7 +111,7 @@ declare const MessageSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
111
111
|
text?: string | undefined;
|
|
112
112
|
url?: string | undefined;
|
|
113
113
|
mimeType?: string | undefined;
|
|
114
|
-
}[] | undefined;
|
|
114
|
+
}[] | null | undefined;
|
|
115
115
|
}>;
|
|
116
116
|
declare const ModelSchema: import("@bpinternal/zui").ZodObject<{
|
|
117
117
|
id: import("@bpinternal/zui").ZodString;
|
|
@@ -200,7 +200,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
200
200
|
id: string;
|
|
201
201
|
}>, "many">>;
|
|
202
202
|
toolResultCallId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
203
|
-
content: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
203
|
+
content: import("@bpinternal/zui").ZodNullable<import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
204
204
|
type: import("@bpinternal/zui").ZodEnum<["text", "image"]>;
|
|
205
205
|
mimeType: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
206
206
|
text: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
@@ -215,7 +215,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
215
215
|
text?: string | undefined;
|
|
216
216
|
url?: string | undefined;
|
|
217
217
|
mimeType?: string | undefined;
|
|
218
|
-
}>, "many">]
|
|
218
|
+
}>, "many">]>>>;
|
|
219
219
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
220
220
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
221
221
|
role: "user" | "assistant";
|
|
@@ -233,7 +233,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
233
233
|
text?: string | undefined;
|
|
234
234
|
url?: string | undefined;
|
|
235
235
|
mimeType?: string | undefined;
|
|
236
|
-
}[] | undefined;
|
|
236
|
+
}[] | null | undefined;
|
|
237
237
|
}, {
|
|
238
238
|
role: "user" | "assistant";
|
|
239
239
|
type?: "text" | "tool_calls" | "tool_result" | "multipart" | undefined;
|
|
@@ -251,7 +251,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
251
251
|
text?: string | undefined;
|
|
252
252
|
url?: string | undefined;
|
|
253
253
|
mimeType?: string | undefined;
|
|
254
|
-
}[] | undefined;
|
|
254
|
+
}[] | null | undefined;
|
|
255
255
|
}>, "many">;
|
|
256
256
|
responseFormat: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodEnum<["text", "json_object"]>>;
|
|
257
257
|
maxTokens: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodNumber>;
|
|
@@ -263,28 +263,28 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
263
263
|
function: import("@bpinternal/zui").ZodObject<{
|
|
264
264
|
name: import("@bpinternal/zui").ZodString;
|
|
265
265
|
description: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
266
|
-
|
|
266
|
+
argumentsSchema: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{}, "passthrough", import("@bpinternal/zui").ZodTypeAny, import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough">, import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough">>>;
|
|
267
267
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
268
268
|
name: string;
|
|
269
269
|
description?: string | undefined;
|
|
270
|
-
|
|
270
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
271
271
|
}, {
|
|
272
272
|
name: string;
|
|
273
273
|
description?: string | undefined;
|
|
274
|
-
|
|
274
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
275
275
|
}>;
|
|
276
276
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
277
277
|
function: {
|
|
278
278
|
name: string;
|
|
279
279
|
description?: string | undefined;
|
|
280
|
-
|
|
280
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
281
281
|
};
|
|
282
282
|
type: "function";
|
|
283
283
|
}, {
|
|
284
284
|
function: {
|
|
285
285
|
name: string;
|
|
286
286
|
description?: string | undefined;
|
|
287
|
-
|
|
287
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
288
288
|
};
|
|
289
289
|
type: "function";
|
|
290
290
|
}>, "many">>;
|
|
@@ -299,6 +299,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
299
299
|
functionName?: string | undefined;
|
|
300
300
|
}>>;
|
|
301
301
|
userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
302
|
+
debug: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
302
303
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
303
304
|
messages: {
|
|
304
305
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
@@ -317,7 +318,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
317
318
|
text?: string | undefined;
|
|
318
319
|
url?: string | undefined;
|
|
319
320
|
mimeType?: string | undefined;
|
|
320
|
-
}[] | undefined;
|
|
321
|
+
}[] | null | undefined;
|
|
321
322
|
}[];
|
|
322
323
|
temperature: number;
|
|
323
324
|
topP: number;
|
|
@@ -332,7 +333,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
332
333
|
function: {
|
|
333
334
|
name: string;
|
|
334
335
|
description?: string | undefined;
|
|
335
|
-
|
|
336
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
336
337
|
};
|
|
337
338
|
type: "function";
|
|
338
339
|
}[] | undefined;
|
|
@@ -341,6 +342,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
341
342
|
functionName?: string | undefined;
|
|
342
343
|
} | undefined;
|
|
343
344
|
userId?: string | undefined;
|
|
345
|
+
debug?: boolean | undefined;
|
|
344
346
|
}, {
|
|
345
347
|
messages: {
|
|
346
348
|
role: "user" | "assistant";
|
|
@@ -359,7 +361,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
359
361
|
text?: string | undefined;
|
|
360
362
|
url?: string | undefined;
|
|
361
363
|
mimeType?: string | undefined;
|
|
362
|
-
}[] | undefined;
|
|
364
|
+
}[] | null | undefined;
|
|
363
365
|
}[];
|
|
364
366
|
maxTokens?: number | undefined;
|
|
365
367
|
model?: {
|
|
@@ -374,7 +376,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
374
376
|
function: {
|
|
375
377
|
name: string;
|
|
376
378
|
description?: string | undefined;
|
|
377
|
-
|
|
379
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
378
380
|
};
|
|
379
381
|
type: "function";
|
|
380
382
|
}[] | undefined;
|
|
@@ -383,6 +385,7 @@ declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObjec
|
|
|
383
385
|
functionName?: string | undefined;
|
|
384
386
|
} | undefined;
|
|
385
387
|
userId?: string | undefined;
|
|
388
|
+
debug?: boolean | undefined;
|
|
386
389
|
}>;
|
|
387
390
|
declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
388
391
|
id: import("@bpinternal/zui").ZodString;
|
|
@@ -419,7 +422,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
419
422
|
id: string;
|
|
420
423
|
}>, "many">>;
|
|
421
424
|
toolResultCallId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
422
|
-
content: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
425
|
+
content: import("@bpinternal/zui").ZodNullable<import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
423
426
|
type: import("@bpinternal/zui").ZodEnum<["text", "image"]>;
|
|
424
427
|
mimeType: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
425
428
|
text: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
@@ -434,7 +437,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
434
437
|
text?: string | undefined;
|
|
435
438
|
url?: string | undefined;
|
|
436
439
|
mimeType?: string | undefined;
|
|
437
|
-
}>, "many">]
|
|
440
|
+
}>, "many">]>>>;
|
|
438
441
|
role: import("@bpinternal/zui").ZodLiteral<"assistant">;
|
|
439
442
|
index: import("@bpinternal/zui").ZodNumber;
|
|
440
443
|
stopReason: import("@bpinternal/zui").ZodEnum<["stop", "max_tokens", "tool_calls", "content_filter", "other"]>;
|
|
@@ -457,7 +460,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
457
460
|
text?: string | undefined;
|
|
458
461
|
url?: string | undefined;
|
|
459
462
|
mimeType?: string | undefined;
|
|
460
|
-
}[] | undefined;
|
|
463
|
+
}[] | null | undefined;
|
|
461
464
|
}, {
|
|
462
465
|
role: "assistant";
|
|
463
466
|
index: number;
|
|
@@ -477,7 +480,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
477
480
|
text?: string | undefined;
|
|
478
481
|
url?: string | undefined;
|
|
479
482
|
mimeType?: string | undefined;
|
|
480
|
-
}[] | undefined;
|
|
483
|
+
}[] | null | undefined;
|
|
481
484
|
}>, "many">;
|
|
482
485
|
usage: import("@bpinternal/zui").ZodObject<{
|
|
483
486
|
inputTokens: import("@bpinternal/zui").ZodNumber;
|
|
@@ -518,7 +521,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
518
521
|
text?: string | undefined;
|
|
519
522
|
url?: string | undefined;
|
|
520
523
|
mimeType?: string | undefined;
|
|
521
|
-
}[] | undefined;
|
|
524
|
+
}[] | null | undefined;
|
|
522
525
|
}[];
|
|
523
526
|
usage: {
|
|
524
527
|
inputTokens: number;
|
|
@@ -549,7 +552,7 @@ declare const GenerateContentOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
|
549
552
|
text?: string | undefined;
|
|
550
553
|
url?: string | undefined;
|
|
551
554
|
mimeType?: string | undefined;
|
|
552
|
-
}[] | undefined;
|
|
555
|
+
}[] | null | undefined;
|
|
553
556
|
}[];
|
|
554
557
|
usage: {
|
|
555
558
|
inputTokens: number;
|
|
@@ -602,7 +605,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
602
605
|
id: string;
|
|
603
606
|
}>, "many">>;
|
|
604
607
|
toolResultCallId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
605
|
-
content: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
608
|
+
content: import("@bpinternal/zui").ZodNullable<import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodUnion<[import("@bpinternal/zui").ZodString, import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodObject<{
|
|
606
609
|
type: import("@bpinternal/zui").ZodEnum<["text", "image"]>;
|
|
607
610
|
mimeType: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
608
611
|
text: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
@@ -617,7 +620,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
617
620
|
text?: string | undefined;
|
|
618
621
|
url?: string | undefined;
|
|
619
622
|
mimeType?: string | undefined;
|
|
620
|
-
}>, "many">]
|
|
623
|
+
}>, "many">]>>>;
|
|
621
624
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
622
625
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
623
626
|
role: "user" | "assistant";
|
|
@@ -635,7 +638,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
635
638
|
text?: string | undefined;
|
|
636
639
|
url?: string | undefined;
|
|
637
640
|
mimeType?: string | undefined;
|
|
638
|
-
}[] | undefined;
|
|
641
|
+
}[] | null | undefined;
|
|
639
642
|
}, {
|
|
640
643
|
role: "user" | "assistant";
|
|
641
644
|
type?: "text" | "tool_calls" | "tool_result" | "multipart" | undefined;
|
|
@@ -653,7 +656,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
653
656
|
text?: string | undefined;
|
|
654
657
|
url?: string | undefined;
|
|
655
658
|
mimeType?: string | undefined;
|
|
656
|
-
}[] | undefined;
|
|
659
|
+
}[] | null | undefined;
|
|
657
660
|
}>, "many">;
|
|
658
661
|
responseFormat: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodEnum<["text", "json_object"]>>;
|
|
659
662
|
maxTokens: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodNumber>;
|
|
@@ -665,28 +668,28 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
665
668
|
function: import("@bpinternal/zui").ZodObject<{
|
|
666
669
|
name: import("@bpinternal/zui").ZodString;
|
|
667
670
|
description: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
668
|
-
|
|
671
|
+
argumentsSchema: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{}, "passthrough", import("@bpinternal/zui").ZodTypeAny, import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough">, import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough">>>;
|
|
669
672
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
670
673
|
name: string;
|
|
671
674
|
description?: string | undefined;
|
|
672
|
-
|
|
675
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
673
676
|
}, {
|
|
674
677
|
name: string;
|
|
675
678
|
description?: string | undefined;
|
|
676
|
-
|
|
679
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
677
680
|
}>;
|
|
678
681
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
679
682
|
function: {
|
|
680
683
|
name: string;
|
|
681
684
|
description?: string | undefined;
|
|
682
|
-
|
|
685
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
683
686
|
};
|
|
684
687
|
type: "function";
|
|
685
688
|
}, {
|
|
686
689
|
function: {
|
|
687
690
|
name: string;
|
|
688
691
|
description?: string | undefined;
|
|
689
|
-
|
|
692
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
690
693
|
};
|
|
691
694
|
type: "function";
|
|
692
695
|
}>, "many">>;
|
|
@@ -701,6 +704,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
701
704
|
functionName?: string | undefined;
|
|
702
705
|
}>>;
|
|
703
706
|
userId: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
707
|
+
debug: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodBoolean>;
|
|
704
708
|
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
705
709
|
messages: {
|
|
706
710
|
type: "text" | "tool_calls" | "tool_result" | "multipart";
|
|
@@ -719,7 +723,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
719
723
|
text?: string | undefined;
|
|
720
724
|
url?: string | undefined;
|
|
721
725
|
mimeType?: string | undefined;
|
|
722
|
-
}[] | undefined;
|
|
726
|
+
}[] | null | undefined;
|
|
723
727
|
}[];
|
|
724
728
|
temperature: number;
|
|
725
729
|
topP: number;
|
|
@@ -732,7 +736,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
732
736
|
function: {
|
|
733
737
|
name: string;
|
|
734
738
|
description?: string | undefined;
|
|
735
|
-
|
|
739
|
+
argumentsSchema?: import("@bpinternal/zui").objectOutputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
736
740
|
};
|
|
737
741
|
type: "function";
|
|
738
742
|
}[] | undefined;
|
|
@@ -741,6 +745,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
741
745
|
functionName?: string | undefined;
|
|
742
746
|
} | undefined;
|
|
743
747
|
userId?: string | undefined;
|
|
748
|
+
debug?: boolean | undefined;
|
|
744
749
|
}, {
|
|
745
750
|
messages: {
|
|
746
751
|
role: "user" | "assistant";
|
|
@@ -759,7 +764,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
759
764
|
text?: string | undefined;
|
|
760
765
|
url?: string | undefined;
|
|
761
766
|
mimeType?: string | undefined;
|
|
762
|
-
}[] | undefined;
|
|
767
|
+
}[] | null | undefined;
|
|
763
768
|
}[];
|
|
764
769
|
maxTokens?: number | undefined;
|
|
765
770
|
model?: {} | undefined;
|
|
@@ -772,7 +777,7 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
772
777
|
function: {
|
|
773
778
|
name: string;
|
|
774
779
|
description?: string | undefined;
|
|
775
|
-
|
|
780
|
+
argumentsSchema?: import("@bpinternal/zui").objectInputType<{}, import("@bpinternal/zui").ZodTypeAny, "passthrough"> | undefined;
|
|
776
781
|
};
|
|
777
782
|
type: "function";
|
|
778
783
|
}[] | undefined;
|
|
@@ -781,8 +786,9 @@ export declare const llm: InterfaceDeclaration<{
|
|
|
781
786
|
functionName?: string | undefined;
|
|
782
787
|
} | undefined;
|
|
783
788
|
userId?: string | undefined;
|
|
789
|
+
debug?: boolean | undefined;
|
|
784
790
|
}>;
|
|
785
|
-
|
|
791
|
+
listLanguageModels: import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>;
|
|
786
792
|
}, import("../integration/definition/generic").BaseEvents>;
|
|
787
793
|
export declare namespace llm {
|
|
788
794
|
type GenerateContentInput = z.infer<typeof GenerateContentInputBaseSchema>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { InterfaceDeclaration } from '../integration/definition';
|
|
2
|
+
import z from '../zui';
|
|
3
|
+
declare const ImageModelSchema: import("@bpinternal/zui").ZodObject<{
|
|
4
|
+
id: import("@bpinternal/zui").ZodString;
|
|
5
|
+
name: import("@bpinternal/zui").ZodString;
|
|
6
|
+
costPerImage: import("@bpinternal/zui").ZodNumber;
|
|
7
|
+
sizes: import("@bpinternal/zui").ZodArray<import("@bpinternal/zui").ZodString, "many">;
|
|
8
|
+
defaultSize: import("@bpinternal/zui").ZodString;
|
|
9
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
10
|
+
id: string;
|
|
11
|
+
name: string;
|
|
12
|
+
costPerImage: number;
|
|
13
|
+
sizes: string[];
|
|
14
|
+
defaultSize: string;
|
|
15
|
+
}, {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
costPerImage: number;
|
|
19
|
+
sizes: string[];
|
|
20
|
+
defaultSize: string;
|
|
21
|
+
}>;
|
|
22
|
+
declare const GenerateContentInputBaseSchema: import("@bpinternal/zui").ZodObject<{
|
|
23
|
+
model: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{
|
|
24
|
+
id: import("@bpinternal/zui").ZodString;
|
|
25
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
26
|
+
id: string;
|
|
27
|
+
}, {
|
|
28
|
+
id: string;
|
|
29
|
+
}>>;
|
|
30
|
+
prompt: import("@bpinternal/zui").ZodString;
|
|
31
|
+
size: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
32
|
+
params: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>>;
|
|
33
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
34
|
+
prompt: string;
|
|
35
|
+
params?: {} | undefined;
|
|
36
|
+
model?: {
|
|
37
|
+
id: string;
|
|
38
|
+
} | undefined;
|
|
39
|
+
size?: string | undefined;
|
|
40
|
+
}, {
|
|
41
|
+
prompt: string;
|
|
42
|
+
params?: {} | undefined;
|
|
43
|
+
model?: {
|
|
44
|
+
id: string;
|
|
45
|
+
} | undefined;
|
|
46
|
+
size?: string | undefined;
|
|
47
|
+
}>;
|
|
48
|
+
declare const GenerateImageOutputSchema: import("@bpinternal/zui").ZodObject<{
|
|
49
|
+
model: import("@bpinternal/zui").ZodString;
|
|
50
|
+
imageUrl: import("@bpinternal/zui").ZodString;
|
|
51
|
+
cost: import("@bpinternal/zui").ZodNumber;
|
|
52
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
53
|
+
imageUrl: string;
|
|
54
|
+
model: string;
|
|
55
|
+
cost: number;
|
|
56
|
+
}, {
|
|
57
|
+
imageUrl: string;
|
|
58
|
+
model: string;
|
|
59
|
+
cost: number;
|
|
60
|
+
}>;
|
|
61
|
+
export declare const textToImage: InterfaceDeclaration<{
|
|
62
|
+
imageModelRef: import("@bpinternal/zui").ZodObject<{
|
|
63
|
+
id: import("@bpinternal/zui").ZodString;
|
|
64
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
65
|
+
id: string;
|
|
66
|
+
}, {
|
|
67
|
+
id: string;
|
|
68
|
+
}>;
|
|
69
|
+
imageGenerationParams: import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>;
|
|
70
|
+
}, {
|
|
71
|
+
generateImage: import("@bpinternal/zui").ZodObject<{
|
|
72
|
+
model: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodRef>;
|
|
73
|
+
prompt: import("@bpinternal/zui").ZodString;
|
|
74
|
+
size: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodString>;
|
|
75
|
+
params: import("@bpinternal/zui").ZodOptional<import("@bpinternal/zui").ZodRef>;
|
|
76
|
+
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
77
|
+
prompt: string;
|
|
78
|
+
params?: {} | undefined;
|
|
79
|
+
model?: {} | undefined;
|
|
80
|
+
size?: string | undefined;
|
|
81
|
+
}, {
|
|
82
|
+
prompt: string;
|
|
83
|
+
params?: {} | undefined;
|
|
84
|
+
model?: {} | undefined;
|
|
85
|
+
size?: string | undefined;
|
|
86
|
+
}>;
|
|
87
|
+
listImageModels: import("@bpinternal/zui").ZodObject<{}, "strip", import("@bpinternal/zui").ZodTypeAny, {}, {}>;
|
|
88
|
+
}, import("../integration/definition/generic").BaseEvents>;
|
|
89
|
+
export declare namespace textToImage {
|
|
90
|
+
type GenerateImageInputSchema = z.infer<typeof GenerateContentInputBaseSchema>;
|
|
91
|
+
type GenerateImageOutputSchema = z.infer<typeof GenerateImageOutputSchema>;
|
|
92
|
+
type ImageModel = z.infer<typeof ImageModelSchema>;
|
|
93
|
+
type ImageModelDetails = Omit<ImageModel, 'id'>;
|
|
94
|
+
}
|
|
95
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botpress/sdk",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.39",
|
|
4
4
|
"description": "Botpress SDK",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"dependencies": {
|
|
17
17
|
"@bpinternal/zui": "0.9.3",
|
|
18
|
-
"@botpress/client": "0.24.
|
|
18
|
+
"@botpress/client": "0.24.2"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"@types/node": "^18.11.17",
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { InterfaceDeclaration } from '../integration/definition';
|
|
2
|
-
export declare const hitl: InterfaceDeclaration<import("../integration/definition/generic").BaseEntities, {
|
|
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>;
|
|
7
|
-
}, "strip", import("@bpinternal/zui").ZodTypeAny, {
|
|
8
|
-
name?: string | undefined;
|
|
9
|
-
pictureUrl?: string | undefined;
|
|
10
|
-
email?: string | undefined;
|
|
11
|
-
}, {
|
|
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;
|
|
28
|
-
}>;
|
|
29
|
-
}, import("../integration/definition/generic").BaseEvents>;
|