@botonic/plugin-ai-agents 0.57.0-rslib-esm.0 → 0.57.0-rslib-esm.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/lib/agents/base-agent.js.map +1 -0
  2. package/lib/agents/index.js.map +1 -0
  3. package/lib/agents/router-agent.js.map +1 -0
  4. package/lib/agents/specialist-agent.js.map +1 -0
  5. package/lib/bot-config-tools.js.map +1 -0
  6. package/lib/constants.js.map +1 -0
  7. package/lib/debug-logger.js.map +1 -0
  8. package/lib/guardrails/index.js.map +1 -0
  9. package/lib/guardrails/input.js.map +1 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/llm-config.js.map +1 -0
  12. package/lib/runners/base-runner.js.map +1 -0
  13. package/lib/runners/index.js.map +1 -0
  14. package/lib/runners/router-runner.js.map +1 -0
  15. package/lib/runners/specialist-runner.js.map +1 -0
  16. package/lib/services/hubtype-api-client.js.map +1 -0
  17. package/lib/services/types.js.map +1 -0
  18. package/lib/structured-output/bot-executor.js.map +1 -0
  19. package/lib/structured-output/carousel.js.map +1 -0
  20. package/lib/structured-output/exit.js.map +1 -0
  21. package/lib/{esm/structured-output → structured-output}/index.d.ts +10 -0
  22. package/lib/{esm/structured-output → structured-output}/index.js +5 -1
  23. package/lib/structured-output/index.js.map +1 -0
  24. package/lib/structured-output/request-contact-info.d.ts +9 -0
  25. package/lib/structured-output/request-contact-info.js +17 -0
  26. package/lib/structured-output/request-contact-info.js.map +1 -0
  27. package/lib/structured-output/text-with-buttons.js.map +1 -0
  28. package/lib/structured-output/text.js.map +1 -0
  29. package/lib/tools/index.js.map +1 -0
  30. package/lib/tools/retrieve-knowledge.js.map +1 -0
  31. package/lib/types.js.map +1 -0
  32. package/package.json +9 -8
  33. package/src/structured-output/index.ts +2 -0
  34. package/src/structured-output/request-contact-info.ts +18 -0
  35. package/lib/esm/agents/base-agent.js.map +0 -1
  36. package/lib/esm/agents/index.js.map +0 -1
  37. package/lib/esm/agents/router-agent.js.map +0 -1
  38. package/lib/esm/agents/specialist-agent.js.map +0 -1
  39. package/lib/esm/bot-config-tools.js.map +0 -1
  40. package/lib/esm/constants.js.map +0 -1
  41. package/lib/esm/debug-logger.js.map +0 -1
  42. package/lib/esm/guardrails/index.js.map +0 -1
  43. package/lib/esm/guardrails/input.js.map +0 -1
  44. package/lib/esm/index.js.map +0 -1
  45. package/lib/esm/llm-config.js.map +0 -1
  46. package/lib/esm/package.json +0 -3
  47. package/lib/esm/runners/base-runner.js.map +0 -1
  48. package/lib/esm/runners/index.js.map +0 -1
  49. package/lib/esm/runners/router-runner.js.map +0 -1
  50. package/lib/esm/runners/specialist-runner.js.map +0 -1
  51. package/lib/esm/services/hubtype-api-client.js.map +0 -1
  52. package/lib/esm/services/types.js.map +0 -1
  53. package/lib/esm/structured-output/bot-executor.js.map +0 -1
  54. package/lib/esm/structured-output/carousel.js.map +0 -1
  55. package/lib/esm/structured-output/exit.js.map +0 -1
  56. package/lib/esm/structured-output/index.js.map +0 -1
  57. package/lib/esm/structured-output/text-with-buttons.js.map +0 -1
  58. package/lib/esm/structured-output/text.js.map +0 -1
  59. package/lib/esm/tools/index.js.map +0 -1
  60. package/lib/esm/tools/retrieve-knowledge.js.map +0 -1
  61. package/lib/esm/types.js.map +0 -1
  62. /package/lib/{esm/agents → agents}/base-agent.d.ts +0 -0
  63. /package/lib/{esm/agents → agents}/base-agent.js +0 -0
  64. /package/lib/{esm/agents → agents}/index.d.ts +0 -0
  65. /package/lib/{esm/agents → agents}/index.js +0 -0
  66. /package/lib/{esm/agents → agents}/router-agent.d.ts +0 -0
  67. /package/lib/{esm/agents → agents}/router-agent.js +0 -0
  68. /package/lib/{esm/agents → agents}/specialist-agent.d.ts +0 -0
  69. /package/lib/{esm/agents → agents}/specialist-agent.js +0 -0
  70. /package/lib/{esm/bot-config-tools.d.ts → bot-config-tools.d.ts} +0 -0
  71. /package/lib/{esm/bot-config-tools.js → bot-config-tools.js} +0 -0
  72. /package/lib/{esm/constants.d.ts → constants.d.ts} +0 -0
  73. /package/lib/{esm/constants.js → constants.js} +0 -0
  74. /package/lib/{esm/debug-logger.d.ts → debug-logger.d.ts} +0 -0
  75. /package/lib/{esm/debug-logger.js → debug-logger.js} +0 -0
  76. /package/lib/{esm/guardrails → guardrails}/index.d.ts +0 -0
  77. /package/lib/{esm/guardrails → guardrails}/index.js +0 -0
  78. /package/lib/{esm/guardrails → guardrails}/input.d.ts +0 -0
  79. /package/lib/{esm/guardrails → guardrails}/input.js +0 -0
  80. /package/lib/{esm/index.d.ts → index.d.ts} +0 -0
  81. /package/lib/{esm/index.js → index.js} +0 -0
  82. /package/lib/{esm/llm-config.d.ts → llm-config.d.ts} +0 -0
  83. /package/lib/{esm/llm-config.js → llm-config.js} +0 -0
  84. /package/lib/{esm/runners → runners}/base-runner.d.ts +0 -0
  85. /package/lib/{esm/runners → runners}/base-runner.js +0 -0
  86. /package/lib/{esm/runners → runners}/index.d.ts +0 -0
  87. /package/lib/{esm/runners → runners}/index.js +0 -0
  88. /package/lib/{esm/runners → runners}/router-runner.d.ts +0 -0
  89. /package/lib/{esm/runners → runners}/router-runner.js +0 -0
  90. /package/lib/{esm/runners → runners}/specialist-runner.d.ts +0 -0
  91. /package/lib/{esm/runners → runners}/specialist-runner.js +0 -0
  92. /package/lib/{esm/services → services}/hubtype-api-client.d.ts +0 -0
  93. /package/lib/{esm/services → services}/hubtype-api-client.js +0 -0
  94. /package/lib/{esm/services → services}/types.d.ts +0 -0
  95. /package/lib/{esm/services → services}/types.js +0 -0
  96. /package/lib/{esm/structured-output → structured-output}/bot-executor.d.ts +0 -0
  97. /package/lib/{esm/structured-output → structured-output}/bot-executor.js +0 -0
  98. /package/lib/{esm/structured-output → structured-output}/carousel.d.ts +0 -0
  99. /package/lib/{esm/structured-output → structured-output}/carousel.js +0 -0
  100. /package/lib/{esm/structured-output → structured-output}/exit.d.ts +0 -0
  101. /package/lib/{esm/structured-output → structured-output}/exit.js +0 -0
  102. /package/lib/{esm/structured-output → structured-output}/text-with-buttons.d.ts +0 -0
  103. /package/lib/{esm/structured-output → structured-output}/text-with-buttons.js +0 -0
  104. /package/lib/{esm/structured-output → structured-output}/text.d.ts +0 -0
  105. /package/lib/{esm/structured-output → structured-output}/text.js +0 -0
  106. /package/lib/{esm/tools → tools}/index.d.ts +0 -0
  107. /package/lib/{esm/tools → tools}/index.js +0 -0
  108. /package/lib/{esm/tools → tools}/retrieve-knowledge.d.ts +0 -0
  109. /package/lib/{esm/tools → tools}/retrieve-knowledge.js +0 -0
  110. /package/lib/{esm/types.d.ts → types.d.ts} +0 -0
  111. /package/lib/{esm/types.js → types.js} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents/base-agent.js","sources":["../../src/agents/base-agent.ts"],"sourcesContent":["import type {\n AgentOutputType,\n InputGuardrail,\n Model,\n ModelSettings,\n} from '@openai/agents'\nimport type { z } from 'zod'\n\nimport { createInputGuardrails } from '../guardrails'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport {\n getOutputInstructions,\n getOutputSchema,\n type OutputSchema,\n} from '../structured-output'\nimport type { GuardrailRule } from '../types'\n\nexport interface BaseAgentOptions {\n name: string\n instructions: string\n llmConfig: LLMConfig\n inputGuardrailRules: GuardrailRule[]\n outputMessagesSchemas?: z.ZodObject[]\n guardrailTrackingContext: GuardrailTrackingContext\n}\n\nexport abstract class BaseAgent {\n protected name: string\n protected instructions: string\n protected llmConfig: LLMConfig\n private inputGuardrailRules: GuardrailRule[]\n private outputMessagesSchemas: z.ZodObject[]\n private guardrailTrackingContext: GuardrailTrackingContext\n\n constructor(options: BaseAgentOptions) {\n this.name = options.name\n this.instructions = options.instructions\n this.llmConfig = options.llmConfig\n this.inputGuardrailRules = options.inputGuardrailRules\n this.outputMessagesSchemas = options.outputMessagesSchemas || []\n this.guardrailTrackingContext = options.guardrailTrackingContext\n }\n\n protected getAgentModelSettings(): ModelSettings {\n const modelSettings: ModelSettings = { ...this.llmConfig.modelSettings }\n\n if (this.llmConfig.modelSettings.reasoning) {\n modelSettings.reasoning = { ...this.llmConfig.modelSettings.reasoning }\n }\n\n if (this.llmConfig.modelSettings.text) {\n modelSettings.text = { ...this.llmConfig.modelSettings.text }\n }\n\n return modelSettings\n }\n\n protected async getInputGuardrails(): Promise<InputGuardrail[]> {\n return await createInputGuardrails(\n this.inputGuardrailRules,\n this.llmConfig,\n this.guardrailTrackingContext\n )\n }\n\n protected getOutputType(): AgentOutputType<typeof OutputSchema> {\n return getOutputSchema(this.outputMessagesSchemas)\n }\n\n protected addOutputInstructions(instructions: string): string {\n return `${instructions}\\n\\n${getOutputInstructions()}`\n }\n\n protected async getModel(): Promise<string | Model> {\n return await this.llmConfig.getModel()\n }\n}\n"],"names":["createInputGuardrails","getOutputInstructions","getOutputSchema","BaseAgent","modelSettings","instructions","options"],"mappings":";;;;;;;;;;;;;;;;AAQqD;AAOxB;AAYtB,MAAeG,SAASA;IAiBnB,wBAAuC;QAC/C,MAAMC,gBAA+B;YAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa;QAAC;QAEvE,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,SAAS,EAAE;YAC1CA,cAAc,SAAS,GAAG;gBAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,SAAS;YAAC;QACxE;QAEA,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE;YACrCA,cAAc,IAAI,GAAG;gBAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI;YAAC;QAC9D;QAEA,OAAOA;IACT;IAEA,MAAgB,qBAAgD;QAC9D,OAAO,MAAMJ,qBAAqBA,CAChC,IAAI,CAAC,mBAAmB,EACxB,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,wBAAwB;IAEjC;IAEU,gBAAsD;QAC9D,OAAOE,eAAeA,CAAC,IAAI,CAAC,qBAAqB;IACnD;IAEU,sBAAsBG,YAAoB,EAAU;QAC5D,OAAO,GAAGA,aAAa,IAAI,EAAEJ,qBAAqBA,IAAI;IACxD;IAEA,MAAgB,WAAoC;QAClD,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ;IACtC;IAzCA,YAAYK,OAAyB,CAAE;QAPvC,uBAAU,QAAV;QACA,uBAAU,gBAAV;QACA,uBAAU,aAAV;QACA,uBAAQ,uBAAR;QACA,uBAAQ,yBAAR;QACA,uBAAQ,4BAAR;QAGE,IAAI,CAAC,IAAI,GAAGA,QAAQ,IAAI;QACxB,IAAI,CAAC,YAAY,GAAGA,QAAQ,YAAY;QACxC,IAAI,CAAC,SAAS,GAAGA,QAAQ,SAAS;QAClC,IAAI,CAAC,mBAAmB,GAAGA,QAAQ,mBAAmB;QACtD,IAAI,CAAC,qBAAqB,GAAGA,QAAQ,qBAAqB,IAAI,EAAE;QAChE,IAAI,CAAC,wBAAwB,GAAGA,QAAQ,wBAAwB;IAClE;AAmCF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents/index.js","sources":["../../src/agents/index.ts"],"sourcesContent":["export { RouterAgent } from './router-agent'\nexport { SpecialistAgent } from './specialist-agent'\n"],"names":["RouterAgent","SpecialistAgent"],"mappings":";;AAA4C;AACQ"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents/router-agent.js","sources":["../../src/agents/router-agent.ts"],"sourcesContent":["import type { ResolvedPlugins } from '@botonic/core'\nimport { Agent, type AgentOutputType, type Handoff } from '@openai/agents'\nimport { RECOMMENDED_PROMPT_PREFIX } from '@openai/agents-core/extensions'\nimport type { z } from 'zod'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport type { OutputSchema } from '../structured-output'\nimport type { AIAgent, Context, GuardrailRule } from '../types'\nimport { BaseAgent } from './base-agent'\n\ninterface RouterAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n name: string\n instructions: string\n llmConfig: LLMConfig\n handoffs: Handoff<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >[]\n inputGuardrailRules: GuardrailRule[]\n outputMessagesSchemas?: z.ZodObject[]\n guardrailTrackingContext: GuardrailTrackingContext\n}\n\nexport class RouterAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseAgent {\n private handoffs: Handoff<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >[]\n private agent!: AIAgent<TPlugins, TExtraData>\n\n private constructor(options: RouterAgentOptions<TPlugins, TExtraData>) {\n super(options)\n this.handoffs = options.handoffs\n }\n\n static async create<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n >(\n options: RouterAgentOptions<TPlugins, TExtraData>\n ): Promise<RouterAgent<TPlugins, TExtraData>> {\n const routerAgent = new RouterAgent<TPlugins, TExtraData>(options)\n const inputGuardrails = await routerAgent.getInputGuardrails()\n\n // Agent.create is typed as Agent<UnknownContext>; we run with Context<TPlugins, TExtraData>.\n const agent = Agent.create({\n name: routerAgent.name,\n model: await routerAgent.getModel(),\n modelSettings: routerAgent.getAgentModelSettings(),\n instructions: routerAgent.addOutputInstructions(\n `${RECOMMENDED_PROMPT_PREFIX}${routerAgent.instructions}`\n ),\n handoffs: routerAgent.handoffs,\n outputType: routerAgent.getOutputType(),\n inputGuardrails,\n }) as AIAgent<TPlugins, TExtraData>\n\n routerAgent.agent = agent\n return routerAgent\n }\n\n getAgent(): AIAgent<TPlugins, TExtraData> {\n return this.agent\n }\n}\n"],"names":["Agent","RECOMMENDED_PROMPT_PREFIX","BaseAgent","RouterAgent","options","routerAgent","inputGuardrails","agent"],"mappings":";;;;;;;;;;;;;;;;;;AAC0E;AACA;AAMlC;AAkBjC,MAAMG,WAAWA,SAGdD,SAASA;IAYjB,aAAa,OAIXE,OAAiD,EACL;QAC5C,MAAMC,cAAc,IAAIF,WAAWA,CAAuBC;QAC1D,MAAME,kBAAkB,MAAMD,YAAY,kBAAkB;QAE5D,6FAA6F;QAC7F,MAAME,QAAQP,YAAY,CAAC;YACzB,MAAMK,YAAY,IAAI;YACtB,OAAO,MAAMA,YAAY,QAAQ;YACjC,eAAeA,YAAY,qBAAqB;YAChD,cAAcA,YAAY,qBAAqB,CAC7C,GAAGJ,yBAAyBA,GAAGI,YAAY,YAAY,EAAE;YAE3D,UAAUA,YAAY,QAAQ;YAC9B,YAAYA,YAAY,aAAa;YACrCC;QACF;QAEAD,YAAY,KAAK,GAAGE;QACpB,OAAOF;IACT;IAEA,WAA0C;QACxC,OAAO,IAAI,CAAC,KAAK;IACnB;IAjCA,YAAoBD,OAAiD,CAAE;QACrE,KAAK,CAACA,UAPR,uBAAQ,YAAR,SAIA,uBAAQ,SAAR;QAIE,IAAI,CAAC,QAAQ,GAAGA,QAAQ,QAAQ;IAClC;AA+BF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agents/specialist-agent.js","sources":["../../src/agents/specialist-agent.ts"],"sourcesContent":["import type { CampaignV2, ContactInfo, ResolvedPlugins } from '@botonic/core'\nimport { Agent, type AgentOutputType, type ModelSettings } from '@openai/agents'\nimport type { z } from 'zod'\nimport { LLM_PROVIDER } from '../constants'\nimport type { DebugLogger } from '../debug-logger'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport type { OutputSchema } from '../structured-output'\nimport {\n createRetrieveKnowledge,\n mandatoryTools,\n RETRIEVE_KNOWLEDGE_TOOL_NAME,\n} from '../tools'\nimport type { AIAgent, Context, GuardrailRule, Tool } from '../types'\nimport { BaseAgent } from './base-agent'\n\ninterface SpecialistAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n name: string\n instructions: string\n tools: Tool<TPlugins, TExtraData>[]\n campaignsContext?: CampaignV2[]\n contactInfo: ContactInfo[]\n inputGuardrailRules: GuardrailRule[]\n sourceIds: string[]\n outputMessagesSchemas?: z.ZodObject[]\n llmConfig: LLMConfig\n logger: DebugLogger\n guardrailTrackingContext: GuardrailTrackingContext\n forceToolNameOverride?: string\n disableForceRetrieveKnowledge?: boolean\n}\n\nexport class SpecialistAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseAgent {\n private tools: Tool<TPlugins, TExtraData>[]\n private logger: DebugLogger\n private agent!: AIAgent<TPlugins, TExtraData>\n private forceToolNameOverride?: string\n private disableForceRetrieveKnowledge?: boolean\n\n private constructor(options: SpecialistAgentOptions<TPlugins, TExtraData>) {\n super({\n name: options.name,\n instructions: options.instructions,\n llmConfig: options.llmConfig,\n inputGuardrailRules: options.inputGuardrailRules,\n outputMessagesSchemas: options.outputMessagesSchemas,\n guardrailTrackingContext: options.guardrailTrackingContext,\n })\n this.instructions = this.addExtraInstructions(\n options.instructions,\n options.contactInfo,\n options.campaignsContext\n )\n this.tools = this.addHubtypeTools(options.tools, options.sourceIds)\n this.logger = options.logger\n this.forceToolNameOverride = options.forceToolNameOverride\n this.disableForceRetrieveKnowledge = options.disableForceRetrieveKnowledge\n }\n\n static async create<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n >(\n options: SpecialistAgentOptions<TPlugins, TExtraData>\n ): Promise<SpecialistAgent<TPlugins, TExtraData>> {\n const specialistAgent = new SpecialistAgent<TPlugins, TExtraData>(options)\n const model = specialistAgent.llmConfig.modelName\n const resolvedModel = await specialistAgent.getModel()\n const hasRetrieveKnowledge = specialistAgent.tools.some(\n tool => tool.name === RETRIEVE_KNOWLEDGE_TOOL_NAME\n )\n const modelSettings =\n specialistAgent.getSpecialistModelSettings(hasRetrieveKnowledge)\n const inputGuardrails = await specialistAgent.getInputGuardrails()\n\n specialistAgent.logger.logModelSettings({\n provider: LLM_PROVIDER,\n model,\n reasoning: modelSettings.reasoning as { effort: string } | undefined,\n text: modelSettings.text as { verbosity: string } | undefined,\n toolChoice: modelSettings.toolChoice,\n hasRetrieveKnowledge,\n })\n\n const agent = new Agent<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >({\n name: specialistAgent.name,\n model: resolvedModel,\n modelSettings,\n instructions: specialistAgent.instructions,\n tools: specialistAgent.tools,\n outputType: specialistAgent.getOutputType(),\n inputGuardrails,\n outputGuardrails: [],\n })\n\n specialistAgent.agent = agent\n return specialistAgent\n }\n\n getAgent(): AIAgent<TPlugins, TExtraData> {\n return this.agent\n }\n\n private getSpecialistModelSettings(\n hasRetrieveKnowledge: boolean\n ): ModelSettings {\n const modelSettings = this.getAgentModelSettings()\n const forceRetrieveKnowledge =\n hasRetrieveKnowledge &&\n !this.forceToolNameOverride &&\n !this.disableForceRetrieveKnowledge\n\n if (forceRetrieveKnowledge) {\n modelSettings.toolChoice = RETRIEVE_KNOWLEDGE_TOOL_NAME\n }\n\n if (this.forceToolNameOverride) {\n modelSettings.toolChoice = this.forceToolNameOverride\n }\n\n return modelSettings\n }\n\n private addExtraInstructions(\n initialInstructions: string,\n contactInfo: ContactInfo[],\n campaignsContext?: CampaignV2[]\n ): string {\n const sections = [\n `<instructions>\\n${initialInstructions.trim()}\\n</instructions>`,\n this.getMetadataInstructions(),\n this.getContactInfoInstructions(contactInfo),\n this.getCampaignInstructions(campaignsContext),\n ].filter(section => section.length > 0)\n\n return this.addOutputInstructions(sections.join('\\n\\n'))\n }\n\n private getContactInfoInstructions(contactInfo: ContactInfo[]): string {\n return `<contact_info_fields>${JSON.stringify(\n contactInfo.map(info => ({\n name: info.name,\n value: info.value,\n })),\n null,\n 0\n )}</contact_info_fields>`\n }\n\n private getMetadataInstructions(): string {\n const metadata = `Current Date: ${new Date().toISOString()}`\n return `<metadata>\\n${metadata}\\n</metadata>`\n }\n\n private getCampaignInstructions(campaignsContext?: CampaignV2[]): string {\n if (!campaignsContext || campaignsContext.length === 0) {\n return ''\n }\n const campaignsWithContext = campaignsContext.filter(\n campaign => campaign.agent_context\n )\n if (campaignsWithContext.length === 0) {\n return ''\n }\n return campaignsWithContext\n .map(\n (campaign, index) =>\n `<campaign_context_${index + 1}>\\n${campaign.agent_context}\\n</campaign_context_${index + 1}>`\n )\n .join('\\n')\n }\n\n private addHubtypeTools(\n tools: Tool<TPlugins, TExtraData>[],\n sourceIds: string[]\n ): Tool<TPlugins, TExtraData>[] {\n const hubtypeTools: Tool[] = [...mandatoryTools]\n if (sourceIds.length > 0) {\n hubtypeTools.push(createRetrieveKnowledge(sourceIds))\n }\n return [...hubtypeTools, ...tools]\n }\n}\n"],"names":["Agent","LLM_PROVIDER","createRetrieveKnowledge","mandatoryTools","RETRIEVE_KNOWLEDGE_TOOL_NAME","BaseAgent","SpecialistAgent","options","specialistAgent","model","resolvedModel","hasRetrieveKnowledge","tool","modelSettings","inputGuardrails","agent","forceRetrieveKnowledge","initialInstructions","contactInfo","campaignsContext","sections","section","JSON","info","metadata","Date","campaignsWithContext","campaign","index","tools","sourceIds","hubtypeTools"],"mappings":";;;;;;;;;;;;;;;;;;;;AACgF;AAErC;AAS1B;AAEuB;AAqBjC,MAAMM,eAAeA,SAGlBD,SAASA;IA2BjB,aAAa,OAIXE,OAAqD,EACL;QAChD,MAAMC,kBAAkB,IAAIF,eAAeA,CAAuBC;QAClE,MAAME,QAAQD,gBAAgB,SAAS,CAAC,SAAS;QACjD,MAAME,gBAAgB,MAAMF,gBAAgB,QAAQ;QACpD,MAAMG,uBAAuBH,gBAAgB,KAAK,CAAC,IAAI,CACrDI,CAAAA,OAAQA,KAAK,IAAI,KAAKR,4BAA4BA;QAEpD,MAAMS,gBACJL,gBAAgB,0BAA0B,CAACG;QAC7C,MAAMG,kBAAkB,MAAMN,gBAAgB,kBAAkB;QAEhEA,gBAAgB,MAAM,CAAC,gBAAgB,CAAC;YACtC,UAAUP,YAAYA;YACtBQ;YACA,WAAWI,cAAc,SAAS;YAClC,MAAMA,cAAc,IAAI;YACxB,YAAYA,cAAc,UAAU;YACpCF;QACF;QA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,EAAEA,QAAQ,SAAS;QAClE,IAAI,CAAC,MAAM,GAAGA,QAAQ,MAAM;QAC5B,IAAI,CAAC,qBAAqB,GAAGA,QAAQ,qBAAqB;QAC1D,IAAI,CAAC,6BAA6B,GAAGA,QAAQ,6BAA6B;IAC5E;AAgIF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bot-config-tools.js","sources":["../src/bot-config-tools.ts"],"sourcesContent":["import type { ToolConfigJSON } from '@botonic/core'\nimport { z } from 'zod'\n\nimport type { CustomTool } from './types'\n\n/**\n * Maps custom AI agent tools to the format expected by bot config (e.g. for flow-builder).\n * Converts each tool's Zod schema to JSON Schema so it can be serialized in the config.\n */\nexport function getToolsForBotConfig(\n customTools: CustomTool[]\n): ToolConfigJSON[] {\n return customTools.map(tool => ({\n name: tool.name,\n description: tool.description,\n schema: z.toJSONSchema(tool.schema, {\n target: 'draft-07',\n }) as ToolConfigJSON['schema'],\n }))\n}\n"],"names":["z","getToolsForBotConfig","customTools","tool"],"mappings":";;;AACuB;AAIvB;;;CAGC,GACM,SAASC,oBAAoBA,CAClCC,WAAyB;IAEzB,OAAOA,YAAY,GAAG,CAACC,CAAAA,OAAS;YAC9B,MAAMA,KAAK,IAAI;YACf,aAAaA,KAAK,WAAW;YAC7B,QAAQH,cAAc,CAACG,KAAK,MAAM,EAAE;gBAClC,QAAQ;YACV;QACF;AACF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sources":["../src/constants.ts"],"sourcesContent":["export const HUBTYPE_API_URL =\n process.env.HUBTYPE_API_URL || 'https://api.hubtype.com'\n\n// LLM Configuration (provider-agnostic; set LLM_PROVIDER=azure|openai)\nexport const LLM_PROVIDERS = {\n AZURE: 'azure',\n OPENAI: 'openai',\n LITELLM: 'litellm',\n} as const\n\nexport type LLMProviderType = (typeof LLM_PROVIDERS)[keyof typeof LLM_PROVIDERS]\n\nexport const LITELLM_TAG_KEYS = {\n BOT_ID: 'bot_id',\n ORG_ID: 'org_id',\n SEPARATOR: ',',\n} as const\n\nexport const LLM_PROVIDER: LLMProviderType =\n (process.env.LLM_PROVIDER as LLMProviderType) || LLM_PROVIDERS.AZURE\nexport const LLM_API_KEY = process.env.LLM_API_KEY // pragma: allowlist secret\nexport const LLM_API_URL = process.env.LLM_API_URL\nexport const LLM_AZURE_API_VERSION =\n process.env.LLM_AZURE_API_VERSION || '2025-01-01-preview'\nexport const LLM_OPENAI_MODEL = process.env.LLM_OPENAI_MODEL || 'gpt-4.1-mini'\n\nexport const isProd = process.env.NODE_ENV === 'production'\n\nexport const MAX_MEMORY_LENGTH = 25\n\nexport const DEFAULT_TIMEOUT_16_SECONDS = 16000\nexport const DEFAULT_MAX_RETRIES = 2\n"],"names":["HUBTYPE_API_URL","process","LLM_PROVIDERS","LITELLM_TAG_KEYS","LLM_PROVIDER","LLM_API_KEY","LLM_API_URL","LLM_AZURE_API_VERSION","LLM_OPENAI_MODEL","isProd","MAX_MEMORY_LENGTH","DEFAULT_TIMEOUT_16_SECONDS","DEFAULT_MAX_RETRIES"],"mappings":"AAAO,MAAMA,eAAeA,GAC1BC,QAAQ,GAAG,CAAC,eAAe,IAAI,0BAAyB;AAE1D,uEAAuE;AAChE,MAAMC,aAAaA,GAAG;IAC3B,OAAO;IACP,QAAQ;IACR,SAAS;AACX,EAAU;AAIH,MAAMC,gBAAgBA,GAAG;IAC9B,QAAQ;IACR,QAAQ;IACR,WAAW;AACb,EAAU;AAEH,MAAMC,YAAYA,GACtBH,QAAQ,GAAG,CAAC,YAAY,IAAwBC,aAAaA,CAAC,KAAK;AAC/D,MAAMG,WAAWA,GAAGJ,QAAQ,GAAG,CAAC,WAAW,CAAC,2BAA2B;CAA5B;AAC3C,MAAMK,WAAWA,GAAGL,QAAQ,GAAG,CAAC,WAAW;AAC3C,MAAMM,qBAAqBA,GAChCN,QAAQ,GAAG,CAAC,qBAAqB,IAAI,qBAAoB;AACpD,MAAMO,gBAAgBA,GAAGP,QAAQ,GAAG,CAAC,gBAAgB,IAAI,eAAc;AAEvE,MAAMQ,MAAMA,GAAGR,oBAAoB,KAAK,aAAY;AAEpD,MAAMS,iBAAiBA,GAAG,GAAE;AAE5B,MAAMC,0BAA0BA,GAAG,MAAK;AACxC,MAAMC,mBAAmBA,GAAG,EAAC"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug-logger.js","sources":["../src/debug-logger.ts"],"sourcesContent":["import {\n type AiAgentArgs,\n AiAgentType,\n type ToolExecution,\n} from '@botonic/core'\nimport type { ModelSettings } from '@openai/agents'\nimport { LLM_PROVIDER } from './constants'\nimport type { AgenticInputMessage, MemoryOptions, RunResult } from './types'\n\nconst PREFIX = '[BotonicPluginAiAgents]'\n\nexport interface DebugLoggerConfig {\n messageHistoryApiVersion: string\n maxRetries: number\n timeout: number\n customToolNames: string[]\n memory: MemoryOptions\n}\n\nexport interface ModelSettingsInfo {\n provider: string\n model: string | undefined\n reasoning?: { effort: string }\n text?: { verbosity: string }\n toolChoice?: string\n hasRetrieveKnowledge: boolean\n}\n\nexport interface DebugLogger {\n logInitialConfig(config: DebugLoggerConfig): void\n logAgentDebugInfo(\n aiAgentArgs: AiAgentArgs,\n toolNames: string[],\n messages: AgenticInputMessage[]\n ): void\n logModelSettings(settings: ModelSettingsInfo): void\n logRunnerStart(\n model: string,\n modelSettings: ModelSettings,\n prompt: string\n ): void\n logRunResult(runResult: RunResult, startTime: number): void\n logGuardrailTriggered(): void\n logRunnerError(startTime: number, error: unknown): void\n logToolExecution(toolExecution: ToolExecution): void\n}\n\nclass EnabledDebugLogger implements DebugLogger {\n logInitialConfig(config: DebugLoggerConfig): void {\n console.log(`${PREFIX} === Plugin Initialization ===`)\n console.log(`${PREFIX} Provider: ${LLM_PROVIDER}`)\n console.log(\n `${PREFIX} Message History API Version: ${config.messageHistoryApiVersion}`\n )\n console.log(`${PREFIX} Max Retries: ${config.maxRetries}`)\n console.log(`${PREFIX} Timeout: ${config.timeout}ms`)\n console.log(\n `${PREFIX} Custom Tools Registered: ${config.customToolNames.join(', ') || 'none'}`\n )\n console.log(`${PREFIX} Memory Options:`, {\n maxMessages: config.memory.maxMessages,\n includeToolCalls: config.memory.includeToolCalls,\n maxFullToolResults: config.memory.maxFullToolResults,\n debugMode: config.memory.debugMode,\n })\n console.log(`${PREFIX} === End Plugin Initialization ===`)\n }\n\n logAgentDebugInfo(\n aiAgentArgs: AiAgentArgs,\n toolNames: string[],\n messages: AgenticInputMessage[]\n ): void {\n console.log(`${PREFIX} === AI Agent Debug Info ===`)\n console.log(`${PREFIX} Agent Name: ${aiAgentArgs.name}`)\n console.log(`${PREFIX} Active Tools: ${JSON.stringify(toolNames)}`)\n if (aiAgentArgs.type === AiAgentType.Specialist) {\n console.log(\n `${PREFIX} Source IDs: ${JSON.stringify(aiAgentArgs.sourceIds || [])}`\n )\n }\n console.log(`${PREFIX} Message History Count: ${messages.length}`)\n console.log(`${PREFIX} Messages: ${JSON.stringify(messages, null, 2)}`)\n console.log(\n `${PREFIX} Input Guardrail Rules: ${aiAgentArgs.inputGuardrailRules?.length || 0}`\n )\n console.log(`${PREFIX} === End Debug Info ===`)\n }\n\n logModelSettings(settings: ModelSettingsInfo): void {\n console.log(`${PREFIX} === Agent Model Settings ===`)\n console.log(\n `${PREFIX} Has Retrieve Knowledge Tool: ${settings.hasRetrieveKnowledge}`\n )\n if (settings.reasoning) {\n console.log(`${PREFIX} Reasoning Effort: ${settings.reasoning.effort}`)\n }\n if (settings.text) {\n console.log(`${PREFIX} Text Verbosity: ${settings.text.verbosity}`)\n }\n if (settings.toolChoice) {\n console.log(`${PREFIX} Tool Choice: ${settings.toolChoice}`)\n }\n console.log(`${PREFIX} === End Model Settings ===`)\n }\n\n logRunnerStart(\n model: string,\n modelSettings: ModelSettings,\n prompt: string\n ): void {\n console.log(`${PREFIX} === Runner Execution Start ===`)\n console.log(`${PREFIX} Model: ${model}`)\n console.log(`${PREFIX} Model Settings: ${JSON.stringify(modelSettings)}`)\n console.log(`${PREFIX} Prompt: ${prompt}`)\n }\n\n logRunResult(runResult: RunResult, startTime: number): void {\n const elapsedMs = Date.now() - startTime\n\n console.log(`${PREFIX} === Runner Execution Complete ===`)\n console.log(`${PREFIX} Execution Time: ${elapsedMs}ms`)\n console.log(`${PREFIX} Output Messages Count: ${runResult.messages.length}`)\n console.log(`${PREFIX} Exit: ${runResult.exit}`)\n console.log(`${PREFIX} Error: ${runResult.error}`)\n console.log(\n `${PREFIX} Tools Executed: ${JSON.stringify(runResult.toolsExecuted.map(t => t.toolName))}`\n )\n if (runResult.inputGuardrailsTriggered.length > 0) {\n console.log(\n `${PREFIX} Input Guardrails Triggered: ${runResult.inputGuardrailsTriggered.length}`\n )\n }\n if (runResult.outputGuardrailsTriggered.length > 0) {\n console.log(\n `${PREFIX} Output Guardrails Triggered: ${runResult.outputGuardrailsTriggered.length}`\n )\n }\n console.log(`${PREFIX} === End Runner Execution ===`)\n }\n\n logGuardrailTriggered(): void {\n console.log(`${PREFIX} Input guardrail triggered`)\n }\n\n logRunnerError(startTime: number, error: unknown): void {\n const elapsedMs = Date.now() - startTime\n console.log(`${PREFIX} Runner execution failed after ${elapsedMs}ms`)\n console.log(`${PREFIX} Error:`, error)\n }\n\n logToolExecution(toolExecution: ToolExecution): void {\n console.log(`${PREFIX} Tool Execution: ${toolExecution.toolName}`)\n console.log(\n `${PREFIX} Tool Arguments: ${JSON.stringify(toolExecution.toolArguments)}`\n )\n console.log(`${PREFIX} Tool Results: ${toolExecution.toolResults}`)\n console.log(\n `${PREFIX} Knowledgebase Sources IDs: ${JSON.stringify(toolExecution.knowledgebaseSourcesIds)}`\n )\n console.log(\n `${PREFIX} Knowledgebase Chunks IDs: ${JSON.stringify(toolExecution.knowledgebaseChunksIds)}`\n )\n }\n}\n\nclass DisabledDebugLogger implements DebugLogger {\n logInitialConfig(): void {\n return\n }\n logAgentDebugInfo(): void {\n return\n }\n logModelSettings(): void {\n return\n }\n logRunnerStart(\n _model: string,\n _modelSettings: ModelSettings,\n _prompt: string\n ): void {\n return\n }\n logRunResult(): void {\n return\n }\n logGuardrailTriggered(): void {\n return\n }\n logRunnerError(): void {\n return\n }\n logToolExecution(): void {\n return\n }\n}\n\nexport function createDebugLogger(enableDebug: boolean): DebugLogger {\n return enableDebug ? new EnabledDebugLogger() : new DisabledDebugLogger()\n}\n"],"names":["AiAgentType","LLM_PROVIDER","PREFIX","EnabledDebugLogger","config","console","aiAgentArgs","toolNames","messages","JSON","settings","model","modelSettings","prompt","runResult","startTime","elapsedMs","Date","t","error","toolExecution","DisabledDebugLogger","_model","_modelSettings","_prompt","createDebugLogger","enableDebug"],"mappings":";;;;;AAIsB;AAEoB;AAG1C,MAAME,MAAMA,GAAG;AAsCf,MAAMC,kBAAkBA;IACtB,iBAAiBC,MAAyB,EAAQ;QAChDC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,8BAA8B,CAAC;QACrDG,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,WAAW,EAAED,YAAYA,EAAE;QACjDI,QAAQ,GAAG,CACT,GAAGH,MAAMA,CAAC,8BAA8B,EAAEE,OAAO,wBAAwB,EAAE;QAE7EC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,cAAc,EAAEE,OAAO,UAAU,EAAE;QACzDC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,UAAU,EAAEE,OAAO,OAAO,CAAC,EAAE,CAAC;QACpDC,QAAQ,GAAG,CACT,GAAGH,MAAMA,CAAC,0BAA0B,EAAEE,OAAO,eAAe,CAAC,IAAI,CAAC,SAAS,QAAQ;QAErFC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,gBAAgB,CAAC,EAAE;YACvC,aAAaE,OAAO,MAAM,CAAC,WAAW;YACtC,kBAAkBA,OAAO,MAAM,CAAC,gBAAgB;YAChD,oBAAoBA,OAAO,MAAM,CAAC,kBAAkB;YACpD,WAAWA,OAAO,MAAM,CAAC,SAAS;QACpC;QACAC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC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,cAA6B,EAC7BC,OAAe,EACT;QACN;IACF;IACA,eAAqB;QACnB;IACF;IACA,wBAA8B;QAC5B;IACF;IACA,iBAAuB;QACrB;IACF;IACA,mBAAyB;QACvB;IACF;AACF;AAEO,SAASC,iBAAiBA,CAACC,WAAoB;IACpD,OAAOA,cAAc,IAAIvB,kBAAkBA,KAAK,IAAIkB,mBAAmBA;AACzE"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardrails/index.js","sources":["../../src/guardrails/index.ts"],"sourcesContent":["export * from './input'\n"],"names":[],"mappings":";AAAuB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardrails/input.js","sources":["../../src/guardrails/input.ts"],"sourcesContent":["import {\n Agent,\n type InputGuardrail,\n type ModelSettings,\n Runner,\n type UserMessageItem,\n} from '@openai/agents'\nimport { z } from 'zod'\nimport { isProd, LLM_PROVIDERS } from '../constants'\nimport type { LLMConfig } from '../llm-config'\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport { TrackFeature, TrackProductName } from '../services/types'\nimport type { GuardrailRule, ResultRawResponse } from '../types'\n\nexport interface GuardrailTrackingContext {\n botId: string\n isTest: boolean\n authToken: string\n inferenceId: string\n}\n\nexport async function createInputGuardrails(\n rules: GuardrailRule[],\n llmConfig: LLMConfig,\n trackingContext: GuardrailTrackingContext\n): Promise<InputGuardrail[]> {\n if (rules.length === 0) {\n return []\n }\n\n return [await buildInputGuardrail(rules, llmConfig, trackingContext)]\n}\n\nasync function buildInputGuardrail(\n rules: GuardrailRule[],\n llmConfig: LLMConfig,\n trackingContext: GuardrailTrackingContext\n): Promise<InputGuardrail> {\n const outputType = z.object(\n Object.fromEntries(\n rules.map(rule => [rule.name, z.boolean().describe(rule.description)])\n )\n )\n const modelSettings = createInputGuardrailModelSettings(llmConfig)\n\n const agent = new Agent({\n name: 'InputGuardrail',\n model: await llmConfig.getModel(),\n modelSettings,\n instructions:\n 'Check if the user triggers some of the following guardrails.',\n outputType,\n })\n\n return {\n name: 'InputGuardrail',\n execute: async ({ input, context }) => {\n const lastMessage = input[input.length - 1] as UserMessageItem\n const runner = new Runner({\n tracingDisabled: true,\n })\n const startTime = Date.now()\n const result = await runner.run(agent, [lastMessage], { context })\n const endTime = Date.now()\n\n await sendGuardrailLlmRunTracking(\n result,\n trackingContext,\n llmConfig,\n startTime,\n endTime\n )\n\n const finalOutput = result.finalOutput as Record<string, boolean>\n if (finalOutput === undefined) {\n throw new Error('Guardrail agent failed to produce output')\n }\n const triggered = Object.values(finalOutput).some(value => value === true)\n const triggeredGuardrails = Object.keys(finalOutput).filter(\n key => finalOutput[key] === true\n )\n return {\n outputInfo: triggeredGuardrails,\n tripwireTriggered: triggered,\n }\n },\n }\n}\n\nfunction createInputGuardrailModelSettings(\n llmConfig: LLMConfig\n): ModelSettings {\n const modelSettings: ModelSettings = {\n ...llmConfig.modelSettings,\n toolChoice: undefined,\n }\n if (llmConfig.modelSettings.reasoning) {\n modelSettings.reasoning = { ...llmConfig.modelSettings.reasoning }\n }\n if (llmConfig.modelSettings.text) {\n modelSettings.text = { ...llmConfig.modelSettings.text }\n }\n return modelSettings\n}\n\nasync function sendGuardrailLlmRunTracking(\n result: {\n rawResponses?: ResultRawResponse[]\n },\n trackingContext: GuardrailTrackingContext,\n llmConfig: LLMConfig,\n startTime: number,\n endTime: number\n): Promise<void> {\n if (!isProd) {\n return\n }\n if (llmConfig.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return\n }\n const rawResponses = result.rawResponses ?? []\n if (rawResponses.length === 0) {\n return\n }\n const totalDuration = endTime - startTime\n const durationPerCall = Math.round(totalDuration / rawResponses.length)\n const temperature =\n (llmConfig.modelSettings.temperature as number | undefined) ?? 0\n const llmRuns = rawResponses.map(response => ({\n inference_id: trackingContext.inferenceId,\n is_test: trackingContext.isTest,\n product_name: TrackProductName.AI_AGENT,\n deployment_name: llmConfig.modelName,\n model_name:\n (response.providerData?.model as string | undefined) ??\n llmConfig.modelName,\n feature: TrackFeature.AI_AGENT_GUARDRAIL,\n api_version: llmConfig.getApiVersion(),\n num_prompt_tokens: response.usage.inputTokens,\n num_completion_tokens: response.usage.outputTokens,\n duration_in_milliseconds: durationPerCall,\n temperature,\n error: null,\n }))\n\n const client = new HubtypeApiClient(trackingContext.authToken)\n await client.trackLlmRuns(trackingContext.botId, {\n llm_runs: llmRuns,\n })\n}\n"],"names":["Agent","Runner","z","isProd","LLM_PROVIDERS","HubtypeApiClient","TrackFeature","TrackProductName","createInputGuardrails","rules","llmConfig","trackingContext","buildInputGuardrail","outputType","Object","rule","modelSettings","createInputGuardrailModelSettings","agent","input","context","lastMessage","runner","startTime","Date","result","endTime","sendGuardrailLlmRunTracking","finalOutput","undefined","Error","triggered","value","triggeredGuardrails","key","rawResponses","totalDuration","durationPerCall","Math","temperature","llmRuns","response","client"],"mappings":";;;;;;;;;;;AAMuB;AACA;AAC6B;AAEa;AACC;AAU3D,eAAeQ,qBAAqBA,CACzCC,KAAsB,EACtBC,SAAoB,EACpBC,eAAyC;IAEzC,IAAIF,MAAM,MAAM,KAAK,GAAG;QACtB,OAAO,EAAE;IACX;IAEA,OAAO;QAAC,MAAMG,mBAAmBA,CAACH,OAAOC,WAAWC;KAAiB;AACvE;AAEA,eAAeC,mBAAmBA,CAChCH,KAAsB,EACtBC,SAAoB,EACpBC,eAAyC;IAEzC,MAAME,aAAaX,QAAQ,CACzBY,OAAO,WAAW,CAChBL,MAAM,GAAG,CAACM,CAAAA,OAAQ;YAACA,KAAK,IAAI;YAAEb,SAAS,GAAG,QAAQ,CAACa,KAAK,WAAW;SAAE;IAGzE,MAAMC,gBAAgBC,iCAAiCA,CAACP;IAExD,MAAMQ,QAAQ,IAAIlB,KAAKA,CAAC;QACtB,MAAM;QACN,OAAO,MAAMU,UAAU,QAAQ;QAC/BM;QACA,cACE;QACFH;IACF;IAEA,OAAO;QACL,MAAM;QACN,SAAS,OAAO,EAAEM,KAAK,EAAEC,OAAO,EAAE;YAChC,MAAMC,cAAcF,KAAK,CAACA,M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Aa,MAAM,KAAK,GAAG;QAC7B;IACF;IACA,MAAMC,gBAAgBV,UAAUH;IAChC,MAAMc,kBAAkBC,KAAK,KAAK,CAACF,gBAAgBD,aAAa,MAAM;IACtE,MAAMI,cACH7B,UAAU,aAAa,CAAC,WAAW,IAA2B;IACjE,MAAM8B,UAAUL,aAAa,GAAG,CAACM,CAAAA,WAAa;YAC5C,cAAc9B,gBAAgB,WAAW;YACzC,SAASA,gBAAgB,MAAM;YAC/B,cAAcJ,yBAAyB;YACvC,iBAAiBG,UAAU,SAAS;YACpC,YACG+B,SAAS,YAAY,EAAE,SACxB/B,UAAU,SAAS;YACrB,SAASJ,+BAA+B;YACxC,aAAaI,UAAU,aAAa;YACpC,mBAAmB+B,SAAS,KAAK,CAAC,WAAW;YAC7C,uBAAuBA,SAAS,KAAK,CAAC,YAAY;YAClD,0BAA0BJ;YAC1BE;YACA,OAAO;QACT;IAEA,MAAMG,SAAS,IAAIrC,gBAAgBA,CAACM,gBAAgB,SAAS;IAC7D,MAAM+B,OAAO,YAAY,CAAC/B,gBAAgB,KAAK,EAAE;QAC/C,UAAU6B;IACZ;AACF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import {\n type AIAgentRouterArgs,\n type AiAgentArgs,\n type AiAgentSpecialistArgs,\n AiAgentType,\n type BotContext,\n type HubtypeAssistantMessage,\n type Plugin,\n type ResolvedPlugins,\n} from '@botonic/core'\nimport { handoff, setTracingDisabled, tool } from '@openai/agents'\nimport { v7 as uuidv7 } from 'uuid'\nimport type { ZodObject } from 'zod'\nimport { RouterAgent, SpecialistAgent } from './agents'\nimport {\n DEFAULT_MAX_RETRIES,\n DEFAULT_TIMEOUT_16_SECONDS,\n isProd,\n MAX_MEMORY_LENGTH,\n} from './constants'\nimport { createDebugLogger, type DebugLogger } from './debug-logger'\nimport { LLMConfig } from './llm-config'\nimport { RouterRunner, SpecialistRunner } from './runners'\nimport { HubtypeApiClient } from './services/hubtype-api-client'\nimport type {\n AgenticInputMessage,\n Context,\n CustomTool,\n InferenceResponse,\n MemoryOptions,\n PluginAiAgentOptions,\n Tool,\n} from './types'\n\nexport default class BotonicPluginAiAgents<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> implements Plugin\n{\n private readonly authToken?: string\n private readonly memory: MemoryOptions\n private readonly logger: DebugLogger\n private readonly timeout: number\n private readonly maxRetries: number\n public toolDefinitions: CustomTool<TPlugins, TExtraData>[] = []\n private readonly localStorageKey: string\n\n constructor(options?: PluginAiAgentOptions<TPlugins, TExtraData>) {\n this.authToken = options?.authToken\n this.toolDefinitions = options?.customTools || []\n this.memory = this.getMemoryOptions(options?.memory)\n this.timeout = options?.timeout ?? DEFAULT_TIMEOUT_16_SECONDS\n this.maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES\n this.logger = createDebugLogger(options?.enableDebug ?? false)\n this.localStorageKey = options?.localStorageKey ?? 'botonicState'\n setTracingDisabled(true)\n\n this.logger.logInitialConfig({\n messageHistoryApiVersion: 'v2',\n maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_16_SECONDS,\n customToolNames: this.toolDefinitions.map(t => t.name),\n memory: this.memory,\n })\n }\n\n private getMemoryOptions(memory?: Partial<MemoryOptions>): MemoryOptions {\n return {\n maxMessages: memory?.maxMessages ?? MAX_MEMORY_LENGTH,\n includeToolCalls: memory?.includeToolCalls ?? true,\n maxFullToolResults: memory?.maxFullToolResults ?? 1,\n debugMode: memory?.debugMode ?? false,\n }\n }\n\n pre(): void {\n return\n }\n\n async getInference(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AiAgentArgs\n ): Promise<InferenceResponse> {\n const authToken = isProd ? botContext.session._access_token : this.authToken\n if (!authToken) {\n throw new Error('Auth token is required')\n }\n\n const inferenceId = uuidv7()\n\n try {\n if (aiAgentArgs.type === AiAgentType.Specialist) {\n return await this.executeSpecialistAIAgent(\n botContext,\n aiAgentArgs,\n authToken,\n inferenceId\n )\n }\n\n if (aiAgentArgs.type === AiAgentType.Router) {\n return await this.executeRouterAIAgent(\n botContext,\n aiAgentArgs,\n authToken,\n inferenceId\n )\n }\n\n throw new Error('Invalid agent type')\n } catch (error) {\n console.error('error plugin returns undefined', error)\n return {\n messages: [],\n toolsExecuted: [],\n memoryLength: 0,\n exit: true,\n error: true,\n inputGuardrailsTriggered: [],\n outputGuardrailsTriggered: [],\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n }\n }\n }\n\n private async executeSpecialistAIAgent(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AiAgentSpecialistArgs,\n authToken: string,\n inferenceId: string\n ) {\n const llmConfig = new LLMConfig({\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n modelName: aiAgentArgs.model,\n verbosity: aiAgentArgs.verbosity,\n botContext,\n reasoningEffort: aiAgentArgs.reasoningEffort,\n })\n\n // Get LLM config, tools and agent\n const { tools, agent } = await this.getSpecialistAgentAndTools(\n botContext,\n aiAgentArgs,\n aiAgentArgs.outputMessagesSchemas || [],\n authToken,\n inferenceId,\n llmConfig\n )\n\n // Get messages\n const messages = await this.getMessages(\n botContext,\n authToken,\n aiAgentArgs.previousHubtypeMessages || []\n )\n\n // Build context\n const context: Context<TPlugins, TExtraData> = {\n authToken,\n knowledgeUsed: {\n query: '',\n sourceIds: [],\n chunksIds: [],\n chunkTexts: [],\n },\n request: botContext,\n }\n\n // Log agent debug info\n this.logger.logAgentDebugInfo(\n aiAgentArgs,\n tools.map(t => t.name),\n messages\n )\n\n // Run agent\n const runner = new SpecialistRunner<TPlugins, TExtraData>(\n agent,\n llmConfig,\n inferenceId,\n this.logger\n )\n return await runner.run(messages, context)\n }\n\n private async executeRouterAIAgent(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AIAgentRouterArgs,\n authToken: string,\n inferenceId: string\n ) {\n const { specialists, name, instructions } = aiAgentArgs\n\n const llmConfig = new LLMConfig({\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n modelName: aiAgentArgs.model,\n verbosity: aiAgentArgs.verbosity,\n botContext,\n reasoningEffort: aiAgentArgs.reasoningEffort,\n })\n\n const specialistsAgents = await Promise.all(\n specialists.map(async specialistData => {\n // If the forceToolNameOverride is set, we force this override for all specialists\n const forceToolNameOverride = aiAgentArgs.forceToolNameOverride\n const reasoningEffort = aiAgentArgs.reasoningEffort\n const disableForceRetrieveKnowledge =\n aiAgentArgs.disableForceRetrieveKnowledge\n\n // Create AiAgentArgs for the specialist, with values from AIAgentRouterArgs\n const aiAgentSpecialistArgs: AiAgentArgs = {\n ...specialistData,\n forceToolNameOverride,\n reasoningEffort,\n disableForceRetrieveKnowledge,\n }\n\n const { agent } = await this.getSpecialistAgentAndTools(\n botContext,\n aiAgentSpecialistArgs,\n aiAgentArgs.outputMessagesSchemas || [],\n authToken,\n inferenceId,\n llmConfig\n )\n\n return handoff(agent, {\n toolNameOverride: specialistData.name,\n toolDescriptionOverride: specialistData.description,\n })\n })\n )\n\n const router = await RouterAgent.create<TPlugins, TExtraData>({\n name,\n instructions,\n llmConfig,\n handoffs: specialistsAgents,\n inputGuardrailRules: aiAgentArgs.inputGuardrailRules || [],\n outputMessagesSchemas: aiAgentArgs.outputMessagesSchemas || [],\n guardrailTrackingContext: {\n botId: botContext.session.bot.id,\n isTest: botContext.session.is_test_integration,\n authToken,\n inferenceId,\n },\n })\n\n // Get messages\n const messages = await this.getMessages(\n botContext,\n authToken,\n aiAgentArgs.previousHubtypeMessages || []\n )\n\n // Build context\n const context: Context<TPlugins, TExtraData> = {\n authToken,\n knowledgeUsed: {\n query: '',\n sourceIds: [],\n chunksIds: [],\n chunkTexts: [],\n },\n request: botContext,\n }\n\n // Run agent\n const routerAgent = router.getAgent()\n const runner = new RouterRunner<TPlugins, TExtraData>(\n routerAgent,\n llmConfig,\n inferenceId,\n this.logger\n )\n\n return await runner.run(messages, context)\n }\n\n private async getSpecialistAgentAndTools(\n botContext: BotContext,\n aiAgentArgs: AiAgentArgs,\n outputMessagesSchemas: ZodObject<any>[],\n authToken: string,\n inferenceId: string,\n llmConfig: LLMConfig\n ) {\n // Build tools\n const tools = this.buildTools(aiAgentArgs)\n\n // Build agent\n const sourceIds =\n aiAgentArgs.type === AiAgentType.Specialist ? aiAgentArgs.sourceIds : []\n\n const specialist = await SpecialistAgent.create<TPlugins, TExtraData>({\n name: aiAgentArgs.name,\n instructions: aiAgentArgs.instructions,\n tools: tools,\n contactInfo: botContext.session.user.contact_info || [],\n inputGuardrailRules: aiAgentArgs.inputGuardrailRules || [],\n sourceIds,\n outputMessagesSchemas: outputMessagesSchemas || [],\n campaignsContext: botContext.input.context?.campaigns_v2,\n logger: this.logger,\n llmConfig,\n guardrailTrackingContext: {\n botId: botContext.session.bot.id,\n isTest: botContext.session.is_test_integration,\n authToken,\n inferenceId,\n },\n forceToolNameOverride: aiAgentArgs.forceToolNameOverride,\n disableForceRetrieveKnowledge: aiAgentArgs.disableForceRetrieveKnowledge,\n })\n const specialistAgent = specialist.getAgent()\n\n return { agent: specialistAgent, tools }\n }\n\n private async getMessages(\n botContext: BotContext,\n authToken: string,\n previousHubtypeMessages: HubtypeAssistantMessage[]\n ): Promise<AgenticInputMessage[]> {\n const hubtypeClient = new HubtypeApiClient(authToken)\n if (!isProd) {\n return await hubtypeClient.getLocalMessages(\n MAX_MEMORY_LENGTH,\n previousHubtypeMessages,\n this.localStorageKey\n )\n }\n\n // Default to V2\n const result = await hubtypeClient.getMessagesV2(\n botContext,\n this.memory,\n previousHubtypeMessages\n )\n return result.messages\n }\n\n private buildTools(aiAgentArgs: AiAgentArgs): Tool<TPlugins, TExtraData>[] {\n const activeTools =\n aiAgentArgs.type === AiAgentType.Router ? [] : aiAgentArgs.activeTools\n const activeToolNames = activeTools.map(tool => tool.name)\n const availableTools = this.toolDefinitions.filter(tool =>\n activeToolNames.includes(tool.name)\n )\n return availableTools.map(toolDefinition => {\n return tool<any, Context<TPlugins, TExtraData>, any>({\n name: toolDefinition.name,\n description: toolDefinition.description,\n parameters: toolDefinition.schema,\n execute: toolDefinition.func,\n })\n })\n }\n}\n\nexport * from './bot-config-tools'\nexport * from './types'\n"],"names":["AiAgentType","handoff","setTracingDisabled","tool","v7","uuidv7","RouterAgent","SpecialistAgent","DEFAULT_MAX_RETRIES","DEFAULT_TIMEOUT_16_SECONDS","isProd","MAX_MEMORY_LENGTH","createDebugLogger","LLMConfig","RouterRunner","SpecialistRunner","HubtypeApiClient","BotonicPluginAiAgents","memory","botContext","aiAgentArgs","authToken","Error","inferenceId","error","console","llmConfig","tools","agent","messages","context","t","runner","specialists","name","instructions","specialistsAgents","Promise","specialistData","forceToolNameOverride","reasoningEffort","disableForceRetrieveKnowledge","aiAgentSpecialistArgs","router","routerAgent","outputMessagesSchemas","sourceIds","specialist","specialistAgent","previousHubtypeMessages","hubtypeClient","result","activeTools","activeToolNames","availableTools","toolDefinition","options"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASsB;AAC4C;AAC/B;AAEoB;AAMnC;AACgD;AAC5B;AACkB;AACM;AAWjD,MAAMiB,qBAAqBA;IAgChC,iBAAiBC,MAA+B,EAAiB;QACvE,OAAO;YACL,aAAaA,QAAQ,eAAeP,iBAAiBA;YACrD,kBAAkBO,QAAQ,oBAAoB;YAC9C,oBAAoBA,QAAQ,sBAAsB;YAClD,WAAWA,QAAQ,aAAa;QAClC;IACF;IAEA,MAAY;QACV;IACF;IAEA,MAAM,aACJC,UAA4C,EAC5CC,WAAwB,EACI;QAC5B,MAAMC,YAAYX,MAAMA,GAAGS,WAAW,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,SAAS;QAC5E,IAAI,CAACE,WAAW;YACd,MAAM,IAAIC,MAAM;QAClB;QAEA,MAAMC,cAAclB,EAAMA;QAE1B,IAAI;YACF,IAAIe,YAAY,IAAI,KAAKpB,sBAAsB,EAAE;gB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AAGA,SAAS;QAC1B,IAAI,CAAC,eAAe,GAAGA,SAAS,eAAe,EAAE;QACjD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,gBAAgB,CAACA,SAAS;QAC7C,IAAI,CAAC,OAAO,GAAGA,SAAS,WAAW/C,0BAA0BA;QAC7D,IAAI,CAAC,UAAU,GAAG+C,SAAS,cAAchD,mBAAmBA;QAC5D,IAAI,CAAC,MAAM,GAAGI,iBAAiBA,CAAC4C,SAAS,eAAe;QACxD,IAAI,CAAC,eAAe,GAAGA,SAAS,mBAAmB;QACnDtD,kBAAkBA,CAAC;QAEnB,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC;YAC3B,0BAA0B;YAC1B,YAAYsD,SAAS,cAAchD,mBAAmBA;YACtD,SAASgD,SAAS,WAAW/C,0BAA0BA;YACvD,iBAAiB,IAAI,CAAC,eAAe,CAAC,GAAG,CAACsB,CAAAA,IAAKA,EAAE,IAAI;YACrD,QAAQ,IAAI,CAAC,MAAM;QACrB;IACF;AA2SF;AAAC;AAEiC;AACX"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llm-config.js","sources":["../src/llm-config.ts"],"sourcesContent":["import {\n type BotContext,\n type ReasoningEffort,\n VerbosityLevel,\n} from '@botonic/core'\nimport {\n type Model,\n type ModelProvider,\n type ModelSettings,\n OpenAIProvider,\n} from '@openai/agents'\nimport OpenAI, { AzureOpenAI } from 'openai'\nimport {\n isProd,\n LITELLM_TAG_KEYS,\n LLM_API_KEY,\n LLM_API_URL,\n LLM_AZURE_API_VERSION,\n LLM_OPENAI_MODEL,\n LLM_PROVIDER,\n LLM_PROVIDERS,\n type LLMProviderType,\n} from './constants'\n\nexport interface LLMConfigParams {\n maxRetries: number\n timeout: number\n modelName: string\n verbosity: VerbosityLevel\n botContext: BotContext\n reasoningEffort?: ReasoningEffort\n}\n\nexport class LLMConfig {\n private readonly maxRetries: number\n private readonly timeout: number\n private readonly botContext: BotContext\n public readonly modelName: string\n public readonly modelSettings: ModelSettings\n public readonly modelProvider: ModelProvider\n\n constructor({\n maxRetries,\n timeout,\n modelName,\n verbosity,\n botContext,\n reasoningEffort,\n }: LLMConfigParams) {\n this.maxRetries = maxRetries\n this.timeout = timeout\n this.botContext = botContext\n this.modelName =\n LLM_PROVIDER === LLM_PROVIDERS.OPENAI ? LLM_OPENAI_MODEL : modelName\n this.modelProvider = this.getModelProvider()\n this.modelSettings = this.getModelSettings(\n modelName,\n verbosity,\n reasoningEffort\n )\n }\n\n async getModel(): Promise<Model> {\n return await this.modelProvider.getModel(this.modelName)\n }\n\n private getModelProvider(): ModelProvider {\n const client = this.getClient()\n return new OpenAIProvider({\n openAIClient: client,\n useResponses: false,\n })\n }\n\n getProviderName(): LLMProviderType {\n if (\n this.botContext.settings.LITELLM_API_URL ||\n LLM_PROVIDER === LLM_PROVIDERS.LITELLM\n ) {\n return LLM_PROVIDERS.LITELLM\n }\n return LLM_PROVIDER\n }\n\n private getClient(): OpenAI | AzureOpenAI {\n if (this.getProviderName() === LLM_PROVIDERS.LITELLM) {\n const litellmUrl =\n this.botContext.settings.LITELLM_API_URL || LLM_API_URL || ''\n return this.getLiteLLMClient(litellmUrl)\n }\n if (LLM_PROVIDER === LLM_PROVIDERS.OPENAI) {\n return this.getOpenAIClient()\n }\n return this.getAzureOpenAiClient()\n }\n\n private buildLiteLLMTags(): { 'x-litellm-tags': string } | undefined {\n const botId = this.botContext.session.bot.id\n const orgId = this.botContext.session.organization_id\n const parts: string[] = []\n if (botId) {\n parts.push(`${LITELLM_TAG_KEYS.BOT_ID}:${botId}`)\n }\n if (orgId) {\n parts.push(`${LITELLM_TAG_KEYS.ORG_ID}:${orgId}`)\n }\n return parts.length > 0\n ? { 'x-litellm-tags': parts.join(LITELLM_TAG_KEYS.SEPARATOR) }\n : undefined\n }\n\n private getLiteLLMClient(litellmUrl: string): OpenAI {\n return new OpenAI({\n apiKey: this.botContext.secrets.LITELLM_API_KEY || LLM_API_KEY,\n baseURL: litellmUrl,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n defaultHeaders: this.buildLiteLLMTags(),\n })\n }\n\n private getOpenAIClient(): OpenAI {\n return new OpenAI({\n apiKey: this.botContext.secrets.AZURE_OPENAI_API_KEY || LLM_API_KEY,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n })\n }\n\n private getAzureOpenAiClient(): AzureOpenAI {\n const baseURL = `${this.botContext.settings.AZURE_OPENAI_API_BASE || LLM_API_URL}openai/`\n\n return new AzureOpenAI({\n apiKey: this.botContext.secrets.AZURE_OPENAI_API_KEY || LLM_API_KEY,\n apiVersion:\n this.botContext.settings.AZURE_OPENAI_API_VERSION ||\n LLM_AZURE_API_VERSION,\n deployment: this.modelName,\n baseURL,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n })\n }\n\n private getModelSettings(\n model: string,\n verbosity: VerbosityLevel,\n reasoningEffort?: ReasoningEffort\n ): ModelSettings {\n if (model.includes('gpt-4')) {\n return {\n temperature: 0,\n text: { verbosity: VerbosityLevel.Medium },\n }\n }\n\n if (reasoningEffort) {\n return {\n reasoning: { effort: reasoningEffort },\n temperature: 1,\n text: { verbosity },\n }\n }\n\n return {\n temperature: 1,\n text: { verbosity },\n }\n }\n\n getApiVersion(): string | undefined {\n if (this.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return undefined\n }\n if (LLM_PROVIDER !== LLM_PROVIDERS.AZURE) {\n return 'NOT_API_VERSION_FOR_OPENAI_PROVIDER'\n }\n return (\n this.botContext.settings.AZURE_OPENAI_API_VERSION || LLM_AZURE_API_VERSION\n )\n }\n}\n"],"names":["VerbosityLevel","OpenAIProvider","OpenAI","AzureOpenAI","isProd","LITELLM_TAG_KEYS","LLM_API_KEY","LLM_API_URL","LLM_AZURE_API_VERSION","LLM_OPENAI_MODEL","LLM_PROVIDER","LLM_PROVIDERS","LLMConfig","client","litellmUrl","botId","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QA;gBAAgB;gBACrC,aAAa;gBACb,MAAM;oBAAED;gBAAU;YACpB;QACF;QAEA,OAAO;YACL,aAAa;YACb,MAAM;gBAAEA;YAAU;QACpB;IACF;IAEA,gBAAoC;QAClC,IAAI,IAAI,CAAC,eAAe,OAAOV,qBAAqB,EAAE;YACpD,OAAOO;QACT;QACA,IAAIR,YAAYA,KAAKC,mBAAmB,EAAE;YACxC,OAAO;QACT;QACA,OACE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,wBAAwB,IAAIH,qBAAqBA;IAE9E;IA9IA,YAAY,EACVe,UAAU,EACVC,OAAO,EACPC,SAAS,EACTJ,SAAS,EACTK,UAAU,EACVJ,eAAe,EACC,CAAE;QAdpB,uBAAiB,cAAjB;QACA,uBAAiB,WAAjB;QACA,uBAAiB,cAAjB;QACA,uBAAgB,aAAhB;QACA,uBAAgB,iBAAhB;QACA,uBAAgB,iBAAhB;QAUE,IAAI,CAAC,UAAU,GAAGC;QAClB,IAAI,CAAC,OAAO,GAAGC;QACf,IAAI,CAAC,UAAU,GAAGE;QAClB,IAAI,CAAC,SAAS,GACZhB,YAAYA,KAAKC,oBAAoB,GAAGF,gBAAgBA,GAAGgB;QAC7D,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB;QAC1C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CACxCA,WACAJ,WACAC;IAEJ;AA4HF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runners/base-runner.js","sources":["../../src/runners/base-runner.ts"],"sourcesContent":["import type {\n OutputMessage,\n ResolvedPlugins,\n ToolExecution,\n} from '@botonic/core'\nimport {\n InputGuardrailTripwireTriggered,\n RunContext,\n Runner,\n RunToolCallItem,\n RunToolCallOutputItem,\n} from '@openai/agents'\nimport { isProd, LLM_PROVIDERS } from '../constants'\nimport type { DebugLogger } from '../debug-logger'\nimport type { LLMConfig } from '../llm-config'\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport { TrackFeature, TrackProductName } from '../services/types'\nimport { RETRIEVE_KNOWLEDGE_TOOL_NAME } from '../tools'\nimport type {\n AgenticInputMessage,\n AgenticOutputMessage,\n AIAgent,\n Context,\n ResultRawResponse,\n RunResult,\n} from '../types'\n\n// Minimal interface matching the properties we actually use from Runner.run() result.\n// This bypasses strict type checking while maintaining type safety for accessed properties.\nexport interface RunnerResult {\n finalOutput?: {\n messages?: OutputMessage[]\n }\n rawResponses?: ResultRawResponse[]\n newItems?: unknown[]\n lastAgent?: { name?: string }\n // biome-ignore lint/suspicious/noExplicitAny: state is a complex internal type\n state?: any\n}\n\nexport abstract class BaseRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n protected agent: AIAgent<TPlugins, TExtraData>\n protected llmConfig: LLMConfig\n protected inferenceId: string\n protected logger: DebugLogger\n\n constructor(\n agent: AIAgent<TPlugins, TExtraData>,\n llmConfig: LLMConfig,\n inferenceId: string,\n logger: DebugLogger\n ) {\n this.agent = agent\n this.llmConfig = llmConfig\n this.inferenceId = inferenceId\n this.logger = logger\n }\n\n async run(\n messages: AgenticInputMessage[],\n context: Context<TPlugins, TExtraData>\n ): Promise<RunResult> {\n const startTime = Date.now()\n\n const runContext = new RunContext(context)\n const prompt = (await this.agent.getSystemPrompt(runContext)) ?? ''\n this.logger.logRunnerStart(\n this.llmConfig.modelName,\n this.llmConfig.modelSettings,\n prompt\n )\n\n try {\n const runner = new Runner({\n tracingDisabled: true,\n })\n const result = (await runner.run(this.agent, messages, {\n context,\n })) as RunnerResult\n const endTime = Date.now()\n\n await this.sendLlmRunTracking(result, context, startTime, endTime)\n\n const runResult = this.buildRunResult(result, context, messages.length)\n\n this.logger.logRunResult(runResult, startTime)\n\n return runResult\n } catch (error) {\n const runResult = this.handleInputGuardrailTripwireTriggered(\n error,\n startTime\n )\n if (runResult) {\n return runResult\n }\n\n this.logger.logRunnerError(startTime, error)\n\n throw error\n }\n }\n\n protected getToolsExecuted(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>\n ): ToolExecution[] {\n const toolResultsByCallId = this.getToolResultsByCallId(result.newItems)\n\n return (\n result.newItems\n ?.filter(item => item instanceof RunToolCallItem)\n .map((item: RunToolCallItem) =>\n this.getToolExecutionInfo(\n item as RunToolCallItem,\n context,\n toolResultsByCallId\n )\n )\n .filter(\n (toolExecution: ToolExecution) => toolExecution.toolName !== ''\n ) || []\n )\n }\n\n private getToolResultsByCallId(\n newItems: unknown[] = []\n ): Map<string, string> {\n const map = new Map<string, string>()\n for (const item of newItems) {\n if (!(item instanceof RunToolCallOutputItem)) {\n continue\n }\n const rawItem = item.rawItem as {\n callId?: string\n output?: string | { type?: string; text?: string }\n }\n const callId = rawItem?.callId\n const output = rawItem?.output\n if (callId == null || output == null) {\n continue\n }\n const text = this.extractToolResult(output)\n if (text != null) {\n map.set(callId, text)\n }\n }\n return map\n }\n\n private extractToolResult(\n output: string | { type?: string; text?: string }\n ): string | undefined {\n if (typeof output === 'string') {\n return output\n }\n return output?.type === 'text' && typeof output?.text === 'string'\n ? output.text\n : undefined\n }\n\n private getToolExecutionInfo(\n item: RunToolCallItem,\n context: Context<TPlugins, TExtraData>,\n toolResultsByCallId: Map<string, string>\n ): ToolExecution {\n if (item.rawItem.type !== 'function_call') {\n return {\n toolName: '',\n toolArguments: {},\n }\n }\n const toolName = item.rawItem.name\n const toolArguments = this.getSafeToolArguments(item.rawItem.arguments)\n const toolResults = item.rawItem.callId\n ? toolResultsByCallId.get(item.rawItem.callId)\n : undefined\n\n const toolExecution: ToolExecution = {\n toolName,\n toolArguments,\n toolResults,\n }\n\n if (toolName === RETRIEVE_KNOWLEDGE_TOOL_NAME) {\n return {\n ...toolExecution,\n knowledgebaseSourcesIds: context.knowledgeUsed.sourceIds,\n knowledgebaseChunksIds: context.knowledgeUsed.chunksIds,\n }\n }\n\n return toolExecution\n }\n\n private getSafeToolArguments(\n rawToolArguments: string\n ): Record<string, unknown> {\n try {\n return JSON.parse(rawToolArguments)\n } catch (_error) {\n return {}\n }\n }\n\n protected buildRunResult(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n memoryLength: number\n ): RunResult {\n const outputMessages = result.finalOutput?.messages || []\n const hasExit =\n outputMessages.length === 0 ||\n outputMessages.some(message => message.type === 'exit')\n\n return {\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n messages: hasExit\n ? []\n : (outputMessages.filter(\n message => message.type !== 'exit'\n ) as AgenticOutputMessage[]),\n toolsExecuted: this.getToolsExecuted(result, context),\n exit: hasExit,\n memoryLength,\n error: false,\n inputGuardrailsTriggered: [],\n outputGuardrailsTriggered: [],\n }\n }\n\n private async sendLlmRunTracking(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n startTime: number,\n endTime: number\n ): Promise<void> {\n if (!isProd) {\n return\n }\n if (this.llmConfig.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return\n }\n const rawResponses = result.rawResponses ?? []\n if (rawResponses.length === 0) {\n return\n }\n const botId = context.request.session.bot.id\n const isTest = context.request.session.is_test_integration\n const totalDuration = endTime - startTime\n const durationPerCall = Math.round(totalDuration / rawResponses.length)\n const temperature =\n (this.llmConfig.modelSettings.temperature as number | undefined) ?? 0\n const llmRuns = rawResponses.map(response => ({\n inference_id: this.inferenceId,\n is_test: isTest,\n product_name: TrackProductName.AI_AGENT,\n deployment_name: this.llmConfig.modelName,\n model_name:\n (response.providerData?.model as string | undefined) ??\n this.llmConfig.modelName,\n feature: TrackFeature.AI_AGENT_RUN,\n api_version: this.llmConfig.getApiVersion(),\n num_prompt_tokens: response.usage.inputTokens,\n num_completion_tokens: response.usage.outputTokens,\n duration_in_milliseconds: durationPerCall,\n temperature,\n error: null,\n }))\n\n const client = new HubtypeApiClient(context.authToken)\n await client.trackLlmRuns(botId, {\n llm_runs: llmRuns,\n })\n }\n\n protected handleInputGuardrailTripwireTriggered(\n error: unknown,\n startTime: number\n ): RunResult | undefined {\n if (error instanceof InputGuardrailTripwireTriggered) {\n const runResult: RunResult = {\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n messages: [],\n memoryLength: 0,\n toolsExecuted: [],\n exit: true,\n error: false,\n inputGuardrailsTriggered: error.result.output.outputInfo,\n outputGuardrailsTriggered: [],\n }\n\n this.logger.logGuardrailTriggered()\n this.logger.logRunResult(runResult, startTime)\n\n return runResult\n }\n }\n}\n"],"names":["InputGuardrailTripwireTriggered","RunContext","Runner","RunToolCallItem","RunToolCallOutputItem","isProd","LLM_PROVIDERS","HubtypeApiClient","TrackFeature","TrackProductName","RETRIEVE_KNOWLEDGE_TOOL_NAME","BaseRunner","messages","context","startTime","Date","runContext","prompt","runner","result","endTime","runResult","error","toolResultsByCallId","item","toolExecution","newItems","map","Map","rawItem","callId","output","text","undefined","toolName","toolArguments","toolResults","rawToolArguments","JSON","_error","memoryLength","outputMessages","hasExit","message","rawResponses","botId","isTest","totalDuration","durationPerCall","Math","temperature","llmRuns","response","client","agent","llmConfig","inferenceId","logger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAWuB;AAC6B;AAGa;AACC;AACX;AAuBhD,MAAeW,UAAUA;IAqB9B,MAAM,IACJC,QAA+B,EAC/BC,OAAsC,EAClB;QACpB,MAAMC,YAAYC,KAAK,GAAG;QAE1B,MAAMC,aAAa,IAAIf,UAAUA,CAACY;QAClC,MAAMI,SAAU,MAAM,IAAI,CAAC,KAAK,CAAC,eAAe,CAACD,eAAgB;QACjE,IAAI,CAAC,MAAM,CAAC,cAAc,CACxB,IAAI,CAAC,SAAS,CAAC,SAAS,EACxB,IAAI,CAAC,SAAS,CAAC,aAAa,EAC5BC;QAGF,IAAI;YACF,MAAMC,SAAS,IAAIhB,MAAMA,CAAC;gBACxB,iBAAiB;YACnB;YACA,MAAMiB,SAAU,MAAMD,OAAO,GAAG,CAAC,IAAI,CAAC,KAAK,EAAEN,UAAU;gBACrDC;YACF;YACA,MAAMO,UAAU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QACvB,IAAIQ,iBAAiBtB,+BAA+BA,EAAE;YACpD,MAAMqB,YAAuB;gBAC3B,mBAAmB;gBACnB,eAAe;gBACf,sBAAsB,EAAE;gBACxB,2BAA2B;gBAC3B,UAAU,EAAE;gBACZ,cAAc;gBACd,eAAe,EAAE;gBACjB,MAAM;gBACN,OAAO;gBACP,0BAA0BC,MAAM,MAAM,CAAC,MAAM,CAAC,UAAU;gBACxD,2BAA2B,EAAE;YAC/B;YAEA,IAAI,CAAC,MAAM,CAAC,qBAAqB;YACjC,IAAI,CAAC,MAAM,CAAC,YAAY,CAACD,WAAWP;YAEpC,OAAOO;QACT;IACF;IAjQA,YACEiC,KAAoC,EACpCC,SAAoB,EACpBC,WAAmB,EACnBC,MAAmB,CACnB;QAVF,uBAAU,SAAV;QACA,uBAAU,aAAV;QACA,uBAAU,eAAV;QACA,uBAAU,UAAV;QAQE,IAAI,CAAC,KAAK,GAAGH;QACb,IAAI,CAAC,SAAS,GAAGC;QACjB,IAAI,CAAC,WAAW,GAAGC;QACnB,IAAI,CAAC,MAAM,GAAGC;IAChB;AAwPF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runners/index.js","sources":["../../src/runners/index.ts"],"sourcesContent":["export { RouterRunner } from './router-runner'\nexport { SpecialistRunner } from './specialist-runner'\n"],"names":["RouterRunner","SpecialistRunner"],"mappings":";;AAA8C;AACQ"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runners/router-runner.js","sources":["../../src/runners/router-runner.ts"],"sourcesContent":["import type { AvailableSpecialist, ResolvedPlugins } from '@botonic/core'\nimport { Handoff } from '@openai/agents'\nimport type { Agent } from '@openai/agents-core'\n\nimport type { Context, RunResult } from '../types'\nimport { BaseRunner, type RunnerResult } from './base-runner'\n\nexport class RouterRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseRunner<TPlugins, TExtraData> {\n protected override buildRunResult(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n memoryLength: number\n ): RunResult {\n const base = super.buildRunResult(result, context, memoryLength)\n\n const availableSpecialists = this.getAvailableSpecialists()\n const startingAgentName = this.agent.name ?? ''\n const lastAgentName = result.lastAgent?.name ?? ''\n\n return {\n ...base,\n startingAgentName,\n lastAgentName,\n availableSpecialists,\n isTransferredToSpecialist: startingAgentName !== lastAgentName,\n }\n }\n\n protected override handleInputGuardrailTripwireTriggered(\n error: unknown,\n startTime: number\n ): RunResult | undefined {\n const runResult = super.handleInputGuardrailTripwireTriggered(\n error,\n startTime\n )\n if (runResult) {\n // Override attributes to match router agent\n runResult.startingAgentName = this.agent.name\n runResult.lastAgentName = this.agent.name\n runResult.availableSpecialists = this.getAvailableSpecialists()\n runResult.isTransferredToSpecialist = false\n\n return runResult\n }\n return undefined\n }\n\n private getAvailableSpecialists(): AvailableSpecialist[] {\n return (this.agent.handoffs ?? []).map(\n (entry: Agent<any, any> | Handoff<any, any>) => {\n const isHandoff = entry instanceof Handoff\n const agent = isHandoff ? entry.agent : (entry as Agent<any, any>)\n const description = isHandoff\n ? entry.toolDescription\n : agent.handoffDescription\n return { name: agent.name, description }\n }\n )\n }\n}\n"],"names":["Handoff","BaseRunner","RouterRunner","result","context","memoryLength","base","availableSpecialists","startingAgentName","lastAgentName","error","startTime","runResult","undefined","entry","isHandoff","agent","description"],"mappings":";;;;;AACwC;AAIqB;AAEtD,MAAME,YAAYA,SAGfD,UAAUA;IACC,eACjBE,MAAoB,EACpBC,OAAsC,EACtCC,YAAoB,EACT;QACX,MAAMC,OAAO,KAAK,CAAC,eAAeH,QAAQC,SAASC;QAEnD,MAAME,uBAAuB,IAAI,CAAC,uBAAuB;QACzD,MAAMC,oBAAoB,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI;QAC7C,MAAMC,gBAAgBN,OAAO,SAAS,EAAE,QAAQ;QAEhD,OAAO;YACL,GAAGG,IAAI;YACPE;YACAC;YACAF;YACA,2BAA2BC,sBAAsBC;QACnD;IACF;IAEmB,sCACjBC,KAAc,EACdC,SAAiB,EACM;QACvB,MAAMC,YAAY,KAAK,CAAC,sCACtBF,OACAC;QAEF,IAAIC,WAAW;YACb,4CAA4C;YAC5CA,UAAU,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI;YAC7CA,UAAU,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI;YACzCA,UAAU,oBAAoB,GAAG,IAAI,CAAC,uBAAuB;YAC7DA,UAAU,yBAAyB,GAAG;YAEtC,OAAOA;QACT;QACA,OAAOC;IACT;IAEQ,0BAAiD;QACvD,OAAQ,KAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAC,EAAG,GAAG,CACpC,CAACC;YACC,MAAMC,YAAYD,iBAAiBd,OAAOA;YAC1C,MAAMgB,QAAQD,YAAYD,MAAM,KAAK,GAAIA;YACzC,MAAMG,cAAcF,YAChBD,MAAM,eAAe,GACrBE,MAAM,kBAAkB;YAC5B,OAAO;gBAAE,MAAMA,MAAM,IAAI;gBAAEC;YAAY;QACzC;IAEJ;AACF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runners/specialist-runner.js","sources":["../../src/runners/specialist-runner.ts"],"sourcesContent":["import type { ResolvedPlugins } from '@botonic/core'\nimport { BaseRunner } from './base-runner'\n\nexport class SpecialistRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseRunner<TPlugins, TExtraData> {}\n"],"names":["BaseRunner","SpecialistRunner"],"mappings":";;;AAC0C;AAEnC,MAAMC,gBAAgBA,SAGnBD,UAAUA;AAAwB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services/hubtype-api-client.js","sources":["../../src/services/hubtype-api-client.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\nimport type { BotContext, HubtypeAssistantMessage } from '@botonic/core'\nimport axios from 'axios'\n\nimport { HUBTYPE_API_URL } from '../constants'\nimport type { AgenticInputMessage, Chunk, MemoryOptions } from '../types'\nimport type {\n GetMessagesV2Result,\n HubtypeAssistantMessageV2,\n HubtypeMessage,\n HubtypeMessageV2,\n HubtypeToolMessageV2,\n MessageHistoryResponseV2,\n MessageHistoryV2Params,\n TrackLlmRunsData,\n} from './types'\n\nexport class HubtypeApiClient {\n private readonly authToken: string\n\n constructor(authToken: string) {\n this.authToken = authToken\n }\n\n async retrieveSimilarChunks(\n query: string,\n sourceIds: string[]\n ): Promise<Chunk[]> {\n const url = `${HUBTYPE_API_URL}/external/v1/ai/knowledge_base/similar_chunks/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n const params = {\n query,\n source_ids: sourceIds,\n num_chunks: 5,\n }\n const response = await axios.post(url, params, { headers })\n const chunks = response.data.chunks.map((chunk: Chunk) => ({\n id: chunk.id,\n text: chunk.text,\n }))\n return chunks\n }\n\n async getLocalMessages(\n maxMemoryLength: number,\n previousHubtypeMessages: HubtypeAssistantMessage[],\n localStorageKey: string\n ): Promise<AgenticInputMessage[]> {\n const localBotonicState =\n typeof globalThis !== 'undefined' && globalThis.localStorage\n ? globalThis.localStorage.getItem(localStorageKey)\n : null\n const botonicState = JSON.parse(localBotonicState || '{}')\n const messages = botonicState.messages\n const filteredMessages = messages\n .filter(message => message.data.text)\n .map(message => ({\n role: message.sentBy === 'user' ? 'user' : 'assistant',\n content: message.data.text,\n }))\n .map(message => this.formatMessage(message))\n const resultMessages = [...filteredMessages, ...previousHubtypeMessages]\n\n return resultMessages.slice(-maxMemoryLength)\n }\n\n async getMessagesV2(\n botContext: BotContext,\n options: MemoryOptions,\n previousHubtypeMessages: HubtypeAssistantMessage[]\n ): Promise<GetMessagesV2Result> {\n const url = `${HUBTYPE_API_URL}/external/v2/ai/agent/message_history/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n const params: MessageHistoryV2Params = {\n last_message_id: botContext.input.message_id,\n max_messages: options.maxMessages,\n include_tool_calls: options.includeToolCalls,\n max_full_tool_results: options.maxFullToolResults,\n debug_mode: options.debugMode,\n }\n\n try {\n const response = await axios.get<MessageHistoryResponseV2>(url, {\n headers,\n params,\n })\n const { messages, conversation_id, truncated } = response.data\n const formattedMessages = [...messages, ...previousHubtypeMessages]\n .map(message => this.formatMessageV2(message))\n .filter((message): message is AgenticInputMessage => message !== null)\n\n return {\n messages: formattedMessages,\n conversationId: conversation_id,\n truncated,\n }\n } catch (error) {\n console.error(error)\n throw new Error('Failed to get messages from Hubtype V2 API')\n }\n }\n\n private formatMessageV2(\n message: HubtypeMessageV2\n ): AgenticInputMessage | null {\n switch (message.role) {\n case 'user':\n return {\n role: 'user',\n content: message.content ?? '',\n }\n case 'assistant': {\n const assistantMessage = message as HubtypeAssistantMessageV2\n // If assistant message has tool_calls, include them for context\n // Using double assertion as the OpenAI API supports this format,\n // but the agents SDK types are more restrictive\n if (\n assistantMessage.tool_calls &&\n assistantMessage.tool_calls.length > 0\n ) {\n return {\n role: 'assistant',\n content: assistantMessage.content ?? '',\n tool_calls: assistantMessage.tool_calls.map(tc => ({\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n } as unknown as AgenticInputMessage\n }\n // Regular assistant message without tool_calls\n return {\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: assistantMessage.content ?? '',\n },\n ],\n status: 'completed',\n }\n }\n case 'tool': {\n // Tool messages provide context about previous tool executions\n // Using double assertion as the OpenAI API supports this format,\n // but the agents SDK types are more restrictive\n const toolMessage = message as HubtypeToolMessageV2\n return {\n role: 'tool',\n tool_call_id: toolMessage.tool_call_id,\n content: toolMessage.content ?? '',\n } as unknown as AgenticInputMessage\n }\n case 'system':\n return {\n role: 'system',\n content: message.content ?? '',\n }\n default:\n throw new Error(\n `Invalid message role: ${(message as HubtypeMessageV2).role}`\n )\n }\n }\n\n async trackLlmRuns(botId: string, data: TrackLlmRunsData): Promise<void> {\n // Not stop the bot execution if the tracking fails, just log the error\n try {\n const url = `${HUBTYPE_API_URL}/external/v2/conversational_apps/${botId}/track_llm_runs/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n await axios.post(url, data, { headers })\n } catch (error) {\n console.error('Failed to track LLM runs:', error)\n }\n }\n\n private formatMessage(message: HubtypeMessage): AgenticInputMessage {\n if (message.role === 'user') {\n return {\n content: message.content,\n role: 'user',\n }\n } else if (message.role === 'assistant') {\n return {\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: message.content,\n },\n ],\n status: 'completed',\n }\n } else {\n throw new Error('Invalid message role')\n }\n }\n}\n"],"names":["axios","HUBTYPE_API_URL","HubtypeApiClient","query","sourceIds","url","headers","params","response","chunks","chunk","maxMemoryLength","previousHubtypeMessages","localStorageKey","localBotonicState","globalThis","botonicState","JSON","messages","filteredMessages","message","resultMessages","botContext","options","conversation_id","truncated","formattedMessages","error","console","Error","assistantMessage","tc","toolMessage","botId","data","authToken"],"mappings":";;;;;AAAA,uDAAuD;;;;;;;;;;;AAE9B;AAEqB;AAavC,MAAME,gBAAgBA;IAO3B,MAAM,sBACJC,KAAa,EACbC,SAAmB,EACD;QAClB,MAAMC,MAAM,GAAGJ,eAAeA,CAAC,8CAA8C,CAAC;QAC9E,MAAMK,UAAU;YACd,gBAAgB;YAChB,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE;QAC3C;QACA,MAAMC,SAAS;YACbJ;YACA,YAAYC;YACZ,YAAY;QACd;QACA,MAAMI,WAAW,MAAMR,UAAU,CAACK,KAAKE,QAAQ;YAAED;QAAQ;QACzD,MAAMG,SAASD,SAAS,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAACE,QAAkB;gBACzD,IAAIA,MAAM,EAAE;gBACZ,MAAMA,MAAM,IAAI;YAClB;QACA,OAAOD;IACT;IAEA,MAAM,iBACJE,eAAuB,EACvBC,uBAAkD,EAClDC,eAAuB,EACS;QAChC,MAAMC,oBACJ,OAAOC,eAAe,eAAeA,W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,MAAM,GAAGJ,eAAeA,CAAC,iCAAiC,EAAEgC,MAAM,gBAAgB,CAAC;YACzF,MAAM3B,UAAU;gBACd,gBAAgB;gBAChB,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE;YAC3C;YACA,MAAMN,UAAU,CAACK,KAAK6B,MAAM;gBAAE5B;YAAQ;QACxC,EAAE,OAAOqB,OAAO;YACdC,QAAQ,KAAK,CAAC,6BAA6BD;QAC7C;IACF;IAEQ,cAAcP,OAAuB,EAAuB;QAClE,IAAIA,QAAQ,IAAI,KAAK,QAAQ;YAC3B,OAAO;gBACL,SAASA,QAAQ,OAAO;gBACxB,MAAM;YACR;QACF,OAAO,IAAIA,QAAQ,IAAI,KAAK,aAAa;YACvC,OAAO;gBACL,MAAM;gBACN,SAAS;oBACP;wBACE,MAAM;wBACN,MAAMA,QAAQ,OAAO;oBACvB;iBACD;gBACD,QAAQ;YACV;QACF,OAAO;YACL,MAAM,IAAIS,MAAM;QAClB;IACF;IA5LA,YAAYM,SAAiB,CAAE;QAF/B,uBAAiB,aAAjB;QAGE,IAAI,CAAC,SAAS,GAAGA;IACnB;AA2LF"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services/types.js","sources":["../../src/services/types.ts"],"sourcesContent":["import type { HubtypeAssistantMessage, HubtypeUserMessage } from '@botonic/core'\nimport type { AgenticInputMessage } from '../types'\n\nexport enum TrackProductName {\n AI_AGENT = 'ai_agent',\n}\n\nexport enum TrackFeature {\n AI_AGENT_RUN = 'ai_agent_run',\n AI_AGENT_GUARDRAIL = 'ai_agent_guardrail',\n}\n\nexport interface LlmRunData {\n inference_id: string\n is_test: boolean\n product_name: string\n deployment_name: string\n model_name: string\n feature: string\n api_version?: string\n num_prompt_tokens: number\n num_completion_tokens: number\n duration_in_milliseconds: number\n temperature: number\n error: string | null\n}\n\nexport interface TrackLlmRunsData {\n llm_runs: LlmRunData[]\n}\n\nexport type HubtypeMessage = HubtypeAssistantMessage | HubtypeUserMessage\n\n// V2 API Types\ninterface HubtypeToolCall {\n id: string\n type: 'function'\n function: {\n name: string\n arguments: string\n }\n}\n\ninterface HubtypeUserMessageV2 {\n role: 'user'\n content: string | null\n}\n\nexport interface HubtypeAssistantMessageV2 {\n role: 'assistant'\n content: string | null\n tool_calls?: HubtypeToolCall[] | null\n}\n\nexport interface HubtypeToolMessageV2 {\n role: 'tool'\n content: string | null\n tool_call_id: string\n}\n\ninterface HubtypeSystemMessageV2 {\n role: 'system'\n content: string | null\n}\n\nexport type HubtypeMessageV2 =\n | HubtypeUserMessageV2\n | HubtypeAssistantMessageV2\n | HubtypeToolMessageV2\n | HubtypeSystemMessageV2\n\nexport interface MessageHistoryResponseV2 {\n messages: HubtypeMessageV2[]\n conversation_id: string | null\n truncated: boolean\n}\n\nexport interface GetMessagesV2Result {\n messages: AgenticInputMessage[]\n conversationId: string | null\n truncated: boolean\n}\n\nexport interface MessageHistoryV2Params {\n last_message_id: string\n max_messages?: number\n include_tool_calls?: boolean\n max_full_tool_results?: number\n debug_mode?: boolean\n}\n"],"names":["TrackProductName","TrackFeature"],"mappings":"AAGO,IAAKA,sBAAgBA,0BAAhBA;;WAAAA;MAEX;AAEM,IAAKC,kBAAYA,0BAAZA;;;WAAAA;MAGX"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/bot-executor.js","sources":["../../src/structured-output/bot-executor.ts"],"sourcesContent":["import { type BotExecutorMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { BotExecutorMessage }\n\nexport const BotExecutorSchema = z\n .object({\n type: z.literal(OutputMessageType.BotExecutor),\n content: z.object({\n text: z.string(),\n buttons: z.array(\n z.object({\n text: z.string(),\n payload: z.string(),\n })\n ),\n }),\n })\n .describe(\n 'A text message with buttons to allow the bot to execute a specific action. Use it only when asked explicitly in the prompt'\n )\n"],"names":["OutputMessageType","z","BotExecutorSchema"],"mappings":";;;;;AAA0E;AACnD;AAIhB,MAAME,iBAAiBA,GAAGD,QACxB,CAAC;IACN,MAAMA,SAAS,CAACD,6BAA6B;IAC7C,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;QACd,SAASA,OAAO,CACdA,QAAQ,CAAC;YACP,MAAMA,QAAQ;YACd,SAASA,QAAQ;QACnB;IAEJ;AACF,GACC,QAAQ,CACP,8HACD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/carousel.js","sources":["../../src/structured-output/carousel.ts"],"sourcesContent":["import { type CarouselMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { CarouselMessage }\n\nexport const CarouselSchema = z\n .object({\n type: z.literal(OutputMessageType.Carousel),\n content: z.object({\n text: z.string().nullable().optional(),\n elements: z.array(\n z.object({\n title: z.string(),\n subtitle: z.string(),\n image: z.string(),\n button: z.object({\n text: z.string(),\n url: z.string().nullable().optional(),\n }),\n })\n ),\n }),\n })\n .describe('A carousel message containing a list of elements')\n"],"names":["OutputMessageType","z","CarouselSchema"],"mappings":";;;;;AAAuE;AAChD;AAIhB,MAAME,cAAcA,GAAGD,QACrB,CAAC;IACN,MAAMA,SAAS,CAACD,0BAA0B;IAC1C,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;QACpC,UAAUA,OAAO,CACfA,QAAQ,CAAC;YACP,OAAOA,QAAQ;YACf,UAAUA,QAAQ;YAClB,OAAOA,QAAQ;YACf,QAAQA,QAAQ,CAAC;gBACf,MAAMA,QAAQ;gBACd,KAAKA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;YACrC;QACF;IAEJ;AACF,GACC,QAAQ,CAAC,oDAAmD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/exit.js","sources":["../../src/structured-output/exit.ts"],"sourcesContent":["import { type ExitMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { ExitMessage }\n\nexport const ExitSchema = z\n .object({\n type: z.literal(OutputMessageType.Exit),\n })\n .describe(\n 'An exit message. This message should only be used to exit the agent due to out of context or the user asking to exit the conversation'\n )\n"],"names":["OutputMessageType","z","ExitSchema"],"mappings":";;;;;AAAmE;AAC5C;AAIhB,MAAME,UAAUA,GAAGD,QACjB,CAAC;IACN,MAAMA,SAAS,CAACD,sBAAsB;AACxC,GACC,QAAQ,CACP,yIACD"}
@@ -47,6 +47,11 @@ export declare const OutputSchema: z.ZodObject<{
47
47
  payload: z.ZodString;
48
48
  }, z.core.$strip>>;
49
49
  }, z.core.$strip>;
50
+ }, z.core.$strip>, z.ZodObject<{
51
+ type: z.ZodLiteral<import("@botonic/core").OutputMessageType.RequestContactInfo>;
52
+ content: z.ZodObject<{
53
+ text: z.ZodString;
54
+ }, z.core.$strip>;
50
55
  }, z.core.$strip>]>>;
51
56
  }, z.core.$strip>;
52
57
  export declare function getOutputSchema(externalOutputMessagesSchemas: z.ZodObject<any>[]): z.ZodObject<{
@@ -93,6 +98,11 @@ export declare function getOutputSchema(externalOutputMessagesSchemas: z.ZodObje
93
98
  payload: z.ZodString;
94
99
  }, z.core.$strip>>;
95
100
  }, z.core.$strip>;
101
+ }, z.core.$strip>, z.ZodObject<{
102
+ type: z.ZodLiteral<import("@botonic/core").OutputMessageType.RequestContactInfo>;
103
+ content: z.ZodObject<{
104
+ text: z.ZodString;
105
+ }, z.core.$strip>;
96
106
  }, z.core.$strip>, ...z.ZodObject<any, z.core.$strip>[]]>>;
97
107
  }, z.core.$strip>;
98
108
  export declare function getOutputInstructions(): string;
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { BotExecutorSchema } from "./bot-executor.js";
3
3
  import { CarouselSchema } from "./carousel.js";
4
4
  import { ExitSchema } from "./exit.js";
5
+ import { RequestContactInfoSchema } from "./request-contact-info.js";
5
6
  import { TextSchema } from "./text.js";
6
7
  import { TextWithButtonsSchema } from "./text-with-buttons.js";
7
8
 
@@ -17,12 +18,15 @@ import { TextWithButtonsSchema } from "./text-with-buttons.js";
17
18
 
18
19
 
19
20
 
21
+
22
+
20
23
  const baseMessageSchemas = [
21
24
  TextSchema,
22
25
  TextWithButtonsSchema,
23
26
  CarouselSchema,
24
27
  ExitSchema,
25
- BotExecutorSchema
28
+ BotExecutorSchema,
29
+ RequestContactInfoSchema
26
30
  ];
27
31
  const OutputSchema = z.object({
28
32
  messages: z.array(z.union(baseMessageSchemas))
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/index.js","sources":["../../src/structured-output/index.ts"],"sourcesContent":["import type { OutputMessage } from '@botonic/core'\nimport { z } from 'zod'\nimport { BotExecutorSchema } from './bot-executor'\nimport { CarouselSchema } from './carousel'\nimport { ExitSchema } from './exit'\nimport { RequestContactInfoSchema } from './request-contact-info'\nimport { TextSchema } from './text'\nimport { TextWithButtonsSchema } from './text-with-buttons'\n\nexport interface Output {\n messages: OutputMessage[]\n}\n\nconst baseMessageSchemas = [\n TextSchema,\n TextWithButtonsSchema,\n CarouselSchema,\n ExitSchema,\n BotExecutorSchema,\n RequestContactInfoSchema,\n] as const\nexport const OutputSchema = z\n .object({\n messages: z.array(z.union(baseMessageSchemas)),\n })\n .describe('The messages to be sent to the user')\n\nexport function getOutputSchema(\n externalOutputMessagesSchemas: z.ZodObject<any>[]\n) {\n return z.object({\n messages: z.array(\n z.union([...baseMessageSchemas, ...externalOutputMessagesSchemas])\n ),\n })\n}\n\nexport function getOutputInstructions(): string {\n const example = {\n messages: [\n {\n type: 'text',\n content: {\n text: 'Hello, how can I help you today?',\n },\n },\n ],\n }\n const output = `Return a JSON that follows the output schema provided. Never return multiple output schemas concatenated by a line break.\\n<example>\\n${JSON.stringify(example)}\\n</example>`\n return `<output>\\n${output}\\n</output>`\n}\n"],"names":["z","BotExecutorSchema","CarouselSchema","ExitSchema","RequestContactInfoSchema","TextSchema","TextWithButtonsSchema","baseMessageSchemas","OutputSchema","getOutputSchema","externalOutputMessagesSchemas","getOutputInstructions","example","output","JSON"],"mappings":";;;;;;;;;;;;;;;AACuB;AAC2B;AACP;AACR;AAC8B;AAC9B;AACwB;AAM3D,MAAMO,kBAAkBA,GAAG;IACzBF,UAAUA;IACVC,qBAAqBA;IACrBJ,cAAcA;IACdC,UAAUA;IACVF,iBAAiBA;IACjBG,wBAAwBA;CACzB;AACM,MAAMI,YAAYA,GAAGR,QACnB,CAAC;IACN,UAAUA,OAAO,CAACA,OAAO,CAACO,kBAAkBA;AAC9C,GACC,QAAQ,CAAC,uCAAsC;AAE3C,SAASE,eAAeA,CAC7BC,6BAAiD;IAEjD,OAAOV,QAAQ,CAAC;QACd,UAAUA,OAAO,CACfA,OAAO,CAAC;eAAIO,kBAAkBA;eAAKG;SAA8B;IAErE;AACF;AAEO,SAASC,qBAAqBA;IACnC,MAAMC,UAAU;QACd,UAAU;YACR;gBACE,MAAM;gBACN,SAAS;oBACP,MAAM;gBACR;YACF;SACD;IACH;IACA,MAAMC,SAAS,CAAC,sIAAsI,EAAEC,KAAK,SAAS,CAACF,SAAS,YAAY,CAAC;IAC7L,OAAO,CAAC,UAAU,EAAEC,OAAO,WAAW,CAAC;AACzC"}
@@ -0,0 +1,9 @@
1
+ import { OutputMessageType, type RequestContactInfoMessage } from '@botonic/core';
2
+ import { z } from 'zod';
3
+ export type { RequestContactInfoMessage };
4
+ export declare const RequestContactInfoSchema: z.ZodObject<{
5
+ type: z.ZodLiteral<OutputMessageType.RequestContactInfo>;
6
+ content: z.ZodObject<{
7
+ text: z.ZodString;
8
+ }, z.core.$strip>;
9
+ }, z.core.$strip>;
@@ -0,0 +1,17 @@
1
+ import { OutputMessageType } from "@botonic/core";
2
+ import { z } from "zod";
3
+
4
+
5
+
6
+
7
+
8
+ const RequestContactInfoSchema = z.object({
9
+ type: z.literal(OutputMessageType.RequestContactInfo),
10
+ content: z.object({
11
+ text: z.string().describe('The text of the message')
12
+ })
13
+ }).describe('A message to request phone number from the user. Use it only when asked explicitly in the prompt.');
14
+
15
+ export { RequestContactInfoSchema };
16
+
17
+ //# sourceMappingURL=request-contact-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/request-contact-info.js","sources":["../../src/structured-output/request-contact-info.ts"],"sourcesContent":["import {\n OutputMessageType,\n type RequestContactInfoMessage,\n} from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { RequestContactInfoMessage }\n\nexport const RequestContactInfoSchema = z\n .object({\n type: z.literal(OutputMessageType.RequestContactInfo),\n content: z.object({\n text: z.string().describe('The text of the message'),\n }),\n })\n .describe(\n 'A message to request phone number from the user. Use it only when asked explicitly in the prompt.'\n )\n"],"names":["OutputMessageType","z","RequestContactInfoSchema"],"mappings":";;;;;AAGsB;AACC;AAIhB,MAAME,wBAAwBA,GAAGD,QAC/B,CAAC;IACN,MAAMA,SAAS,CAACD,oCAAoC;IACpD,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ,GAAG,QAAQ,CAAC;IAC5B;AACF,GACC,QAAQ,CACP,qGACD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/text-with-buttons.js","sources":["../../src/structured-output/text-with-buttons.ts"],"sourcesContent":["import { OutputMessageType, type TextWithButtonsMessage } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { TextWithButtonsMessage }\n\nexport const TextWithButtonsSchema = z\n .object({\n type: z.literal(OutputMessageType.TextWithButtons),\n content: z.object({\n text: z.string(),\n buttons: z.array(\n z.object({\n text: z.string(),\n url: z.string().nullable().optional(),\n target: z\n .enum(['_blank', '_self'])\n .default('_blank')\n .nullable()\n .optional()\n .describe(\n 'The target of the button when it has an url. If not provided, it will default to _blank.'\n ),\n })\n ),\n }),\n })\n .describe(\n 'A text message with buttons to allow the user to use quick replies'\n )\n"],"names":["OutputMessageType","z","TextWithButtonsSchema"],"mappings":";;;;;AAA8E;AACvD;AAIhB,MAAME,qBAAqBA,GAAGD,QAC5B,CAAC;IACN,MAAMA,SAAS,CAACD,iCAAiC;IACjD,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;QACd,SAASA,OAAO,CACdA,QAAQ,CAAC;YACP,MAAMA,QAAQ;YACd,KAAKA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;YACnC,QAAQA,SACD,CAAC;gBAAC;gBAAU;aAAQ,EACxB,OAAO,CAAC,UACR,QAAQ,GACR,QAAQ,GACR,QAAQ,CACP;QAEN;IAEJ;AACF,GACC,QAAQ,CACP,sEACD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-output/text.js","sources":["../../src/structured-output/text.ts"],"sourcesContent":["import { OutputMessageType, type TextMessage } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { TextMessage }\n\nexport const TextSchema = z\n .object({\n type: z.literal(OutputMessageType.Text),\n content: z.object({\n text: z.string(),\n }),\n })\n .describe('A text message')\n"],"names":["OutputMessageType","z","TextSchema"],"mappings":";;;;;AAAmE;AAC5C;AAIhB,MAAME,UAAUA,GAAGD,QACjB,CAAC;IACN,MAAMA,SAAS,CAACD,sBAAsB;IACtC,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;IAChB;AACF,GACC,QAAQ,CAAC,kBAAiB"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools/index.js","sources":["../../src/tools/index.ts"],"sourcesContent":["import type { Tool } from '../types'\n\nexport {\n createRetrieveKnowledge,\n RETRIEVE_KNOWLEDGE_TOOL_NAME,\n} from './retrieve-knowledge'\n\nexport const mandatoryTools: Tool[] = []\n"],"names":["createRetrieveKnowledge","RETRIEVE_KNOWLEDGE_TOOL_NAME","mandatoryTools"],"mappings":";AAK6B;AAEtB,MAAME,cAAcA,GAAW,EAAE"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools/retrieve-knowledge.js","sources":["../../src/tools/retrieve-knowledge.ts"],"sourcesContent":["import { type RunContext, tool } from '@openai/agents'\nimport { z } from 'zod'\n\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport type { Context } from '../types'\n\nexport const RETRIEVE_KNOWLEDGE_TOOL_NAME = 'retrieve_knowledge'\n\nexport const createRetrieveKnowledge = (sourceIds: string[]) =>\n tool({\n name: RETRIEVE_KNOWLEDGE_TOOL_NAME,\n description:\n 'Consult the knowledge base for information before answering. Use this tool to make sure the information you provide is faithful.',\n parameters: z.object({\n query: z.string().describe('The query to search the knowledge base for'),\n }),\n execute: async (\n input: { query: string },\n runContext?: RunContext<Context>\n ): Promise<string[]> => {\n const context = runContext?.context\n const query = input.query\n if (!context) {\n throw new Error('Context is required')\n }\n const client = new HubtypeApiClient(context.authToken)\n const chunks = await client.retrieveSimilarChunks(query, sourceIds)\n const chunksIds = chunks.map(chunk => chunk.id)\n const chunkTexts = chunks.map(chunk => chunk.text)\n\n context.knowledgeUsed = {\n query,\n sourceIds,\n chunksIds,\n chunkTexts,\n }\n\n return chunkTexts\n },\n })\n"],"names":["tool","z","HubtypeApiClient","RETRIEVE_KNOWLEDGE_TOOL_NAME","createRetrieveKnowledge","sourceIds","input","runContext","context","query","Error","client","chunks","chunksIds","chunk","chunkTexts"],"mappings":";;;;;;;AAAsD;AAC/B;AAE0C;AAG1D,MAAMG,4BAA4BA,GAAG,qBAAoB;AAEzD,MAAMC,uBAAuBA,GAAG,CAACC,YACtCL,IAAIA,CAAC;QACH,MAAMG,4BAA4BA;QAClC,aACE;QACF,YAAYF,QAAQ,CAAC;YACnB,OAAOA,QAAQ,GAAG,QAAQ,CAAC;QAC7B;QACA,SAAS,OACPK,OACAC;YAEA,MAAMC,UAAUD,YAAY;YAC5B,MAAME,QAAQH,MAAM,KAAK;YACzB,IAAI,CAACE,SAAS;gBACZ,MAAM,IAAIE,MAAM;YAClB;YACA,MAAMC,SAAS,IAAIT,gBAAgBA,CAACM,QAAQ,SAAS;YACrD,MAAMI,SAAS,MAAMD,OAAO,qBAAqB,CAACF,OAAOJ;YACzD,MAAMQ,YAAYD,OAAO,GAAG,CAACE,CAAAA,QAASA,MAAM,EAAE;YAC9C,MAAMC,aAAaH,OAAO,GAAG,CAACE,CAAAA,QAASA,MAAM,IAAI;YAEjDN,QAAQ,aAAa,GAAG;gBACtBC;gBACAJ;gBACAQ;gBACAE;YACF;YAEA,OAAOA;QACT;IACF,GAAE"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["import type {\n AgenticOutputMessage,\n AiAgentArgs,\n BotContext,\n GuardrailRule,\n InferenceResponse,\n ResolvedPlugins,\n RunResult,\n} from '@botonic/core'\nimport type {\n Agent,\n AgentInputItem,\n AgentOutputType,\n RunContext as OpenAIRunContext,\n Tool as OpenAITool,\n} from '@openai/agents'\nimport type { ZodType } from 'zod'\n\nimport type { OutputSchema } from './structured-output'\n\nexport interface Context<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n authToken: string\n knowledgeUsed: {\n query: string\n sourceIds: string[]\n chunksIds: string[]\n chunkTexts: string[]\n }\n request: BotContext<TPlugins, TExtraData>\n}\n\nexport type RunContext<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = OpenAIRunContext<Context<TPlugins, TExtraData>>\n\nexport interface CustomTool<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n name: string\n description: string\n schema: ZodType\n func: (\n input?: any,\n runContext?: RunContext<TPlugins, TExtraData>\n ) => Promise<any>\n}\n\nexport interface Chunk {\n id: string\n text: string\n}\n\nexport type Tool<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = OpenAITool<Context<TPlugins, TExtraData>>\n\nexport type AIAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = Agent<Context<TPlugins, TExtraData>, AgentOutputType<typeof OutputSchema>>\n\nexport interface MemoryOptions {\n maxMessages: number\n includeToolCalls: boolean\n maxFullToolResults: number\n debugMode: boolean\n}\n\nexport interface PluginAiAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n authToken?: string\n customTools?: CustomTool<TPlugins, TExtraData>[]\n maxRetries?: number\n timeout?: number\n memory?: Partial<MemoryOptions>\n /** Enable debug logging for AI agent configuration and execution details. */\n enableDebug?: boolean\n /** Key for the local storage to to get messages in local development mode */\n localStorageKey?: string\n}\n\nexport interface ResultRawResponse {\n usage: {\n inputTokens: number\n outputTokens: number\n }\n providerData?: Record<string, unknown>\n}\n\nexport type AgenticInputMessage = AgentInputItem\n\nexport type {\n AgenticOutputMessage,\n AiAgentArgs,\n GuardrailRule,\n InferenceResponse,\n RunResult,\n}\n"],"names":[],"mappings":"AAyGC"}
package/package.json CHANGED
@@ -1,20 +1,21 @@
1
1
  {
2
+ "type": "module",
2
3
  "name": "@botonic/plugin-ai-agents",
3
- "version": "0.57.0-rslib-esm.0",
4
- "main": "./lib/esm/index.js",
5
- "module": "./lib/esm/index.js",
4
+ "version": "0.57.0-rslib-esm.2",
5
+ "main": "./lib/index.js",
6
+ "module": "./lib/index.js",
6
7
  "description": "Use AI Agents to generate your contents",
7
8
  "scripts": {
8
- "build": "node ../../scripts/build/clean.mjs && rslib build --no-env",
9
- "build:watch": "node ../../scripts/build/clean.mjs && rslib build --watch --no-env",
10
- "test": "../../node_modules/.bin/jest --coverage",
9
+ "build": "rslib build --no-env",
10
+ "build:watch": "rslib build --watch --no-env",
11
+ "test": "vitest run --coverage",
11
12
  "prepublishOnly": "npm run build && npm run test && npm run lint",
12
13
  "lint": "biome check --write src/ tests/",
13
14
  "lint:check": "biome check src/ tests/",
14
15
  "format": "biome format --write src/ tests/"
15
16
  },
16
17
  "dependencies": {
17
- "@botonic/core": "^0.57.0-rslib-esm.0",
18
+ "@botonic/core": "0.57.0-rslib-esm.2",
18
19
  "@openai/agents": "^0.10.1",
19
20
  "axios": "^1.18.1",
20
21
  "openai": "^6.36.0",
@@ -46,5 +47,5 @@
46
47
  "javascript"
47
48
  ],
48
49
  "author": "",
49
- "types": "./lib/esm/index.d.ts"
50
+ "types": "./lib/index.d.ts"
50
51
  }
@@ -3,6 +3,7 @@ import { z } from 'zod'
3
3
  import { BotExecutorSchema } from './bot-executor'
4
4
  import { CarouselSchema } from './carousel'
5
5
  import { ExitSchema } from './exit'
6
+ import { RequestContactInfoSchema } from './request-contact-info'
6
7
  import { TextSchema } from './text'
7
8
  import { TextWithButtonsSchema } from './text-with-buttons'
8
9
 
@@ -16,6 +17,7 @@ const baseMessageSchemas = [
16
17
  CarouselSchema,
17
18
  ExitSchema,
18
19
  BotExecutorSchema,
20
+ RequestContactInfoSchema,
19
21
  ] as const
20
22
  export const OutputSchema = z
21
23
  .object({
@@ -0,0 +1,18 @@
1
+ import {
2
+ OutputMessageType,
3
+ type RequestContactInfoMessage,
4
+ } from '@botonic/core'
5
+ import { z } from 'zod'
6
+
7
+ export type { RequestContactInfoMessage }
8
+
9
+ export const RequestContactInfoSchema = z
10
+ .object({
11
+ type: z.literal(OutputMessageType.RequestContactInfo),
12
+ content: z.object({
13
+ text: z.string().describe('The text of the message'),
14
+ }),
15
+ })
16
+ .describe(
17
+ 'A message to request phone number from the user. Use it only when asked explicitly in the prompt.'
18
+ )
@@ -1 +0,0 @@
1
- {"version":3,"file":"agents/base-agent.js","sources":["../../../src/agents/base-agent.ts"],"sourcesContent":["import type {\n AgentOutputType,\n InputGuardrail,\n Model,\n ModelSettings,\n} from '@openai/agents'\nimport type { z } from 'zod'\n\nimport { createInputGuardrails } from '../guardrails'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport {\n getOutputInstructions,\n getOutputSchema,\n type OutputSchema,\n} from '../structured-output'\nimport type { GuardrailRule } from '../types'\n\nexport interface BaseAgentOptions {\n name: string\n instructions: string\n llmConfig: LLMConfig\n inputGuardrailRules: GuardrailRule[]\n outputMessagesSchemas?: z.ZodObject[]\n guardrailTrackingContext: GuardrailTrackingContext\n}\n\nexport abstract class BaseAgent {\n protected name: string\n protected instructions: string\n protected llmConfig: LLMConfig\n private inputGuardrailRules: GuardrailRule[]\n private outputMessagesSchemas: z.ZodObject[]\n private guardrailTrackingContext: GuardrailTrackingContext\n\n constructor(options: BaseAgentOptions) {\n this.name = options.name\n this.instructions = options.instructions\n this.llmConfig = options.llmConfig\n this.inputGuardrailRules = options.inputGuardrailRules\n this.outputMessagesSchemas = options.outputMessagesSchemas || []\n this.guardrailTrackingContext = options.guardrailTrackingContext\n }\n\n protected getAgentModelSettings(): ModelSettings {\n const modelSettings: ModelSettings = { ...this.llmConfig.modelSettings }\n\n if (this.llmConfig.modelSettings.reasoning) {\n modelSettings.reasoning = { ...this.llmConfig.modelSettings.reasoning }\n }\n\n if (this.llmConfig.modelSettings.text) {\n modelSettings.text = { ...this.llmConfig.modelSettings.text }\n }\n\n return modelSettings\n }\n\n protected async getInputGuardrails(): Promise<InputGuardrail[]> {\n return await createInputGuardrails(\n this.inputGuardrailRules,\n this.llmConfig,\n this.guardrailTrackingContext\n )\n }\n\n protected getOutputType(): AgentOutputType<typeof OutputSchema> {\n return getOutputSchema(this.outputMessagesSchemas)\n }\n\n protected addOutputInstructions(instructions: string): string {\n return `${instructions}\\n\\n${getOutputInstructions()}`\n }\n\n protected async getModel(): Promise<string | Model> {\n return await this.llmConfig.getModel()\n }\n}\n"],"names":["createInputGuardrails","getOutputInstructions","getOutputSchema","BaseAgent","modelSettings","instructions","options"],"mappings":";;;;;;;;;;;;;;;;AAQqD;AAOxB;AAYtB,MAAeG,SAASA;IAiBnB,wBAAuC;QAC/C,MAAMC,gBAA+B;YAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa;QAAC;QAEvE,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,SAAS,EAAE;YAC1CA,cAAc,SAAS,GAAG;gBAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,SAAS;YAAC;QACxE;QAEA,IAAI,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE;YACrCA,cAAc,IAAI,GAAG;gBAAE,GAAG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI;YAAC;QAC9D;QAEA,OAAOA;IACT;IAEA,MAAgB,qBAAgD;QAC9D,OAAO,MAAMJ,qBAAqBA,CAChC,IAAI,CAAC,mBAAmB,EACxB,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,wBAAwB;IAEjC;IAEU,gBAAsD;QAC9D,OAAOE,eAAeA,CAAC,IAAI,CAAC,qBAAqB;IACnD;IAEU,sBAAsBG,YAAoB,EAAU;QAC5D,OAAO,GAAGA,aAAa,IAAI,EAAEJ,qBAAqBA,IAAI;IACxD;IAEA,MAAgB,WAAoC;QAClD,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,QAAQ;IACtC;IAzCA,YAAYK,OAAyB,CAAE;QAPvC,uBAAU,QAAV;QACA,uBAAU,gBAAV;QACA,uBAAU,aAAV;QACA,uBAAQ,uBAAR;QACA,uBAAQ,yBAAR;QACA,uBAAQ,4BAAR;QAGE,IAAI,CAAC,IAAI,GAAGA,QAAQ,IAAI;QACxB,IAAI,CAAC,YAAY,GAAGA,QAAQ,YAAY;QACxC,IAAI,CAAC,SAAS,GAAGA,QAAQ,SAAS;QAClC,IAAI,CAAC,mBAAmB,GAAGA,QAAQ,mBAAmB;QACtD,IAAI,CAAC,qBAAqB,GAAGA,QAAQ,qBAAqB,IAAI,EAAE;QAChE,IAAI,CAAC,wBAAwB,GAAGA,QAAQ,wBAAwB;IAClE;AAmCF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"agents/index.js","sources":["../../../src/agents/index.ts"],"sourcesContent":["export { RouterAgent } from './router-agent'\nexport { SpecialistAgent } from './specialist-agent'\n"],"names":["RouterAgent","SpecialistAgent"],"mappings":";;AAA4C;AACQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"agents/router-agent.js","sources":["../../../src/agents/router-agent.ts"],"sourcesContent":["import type { ResolvedPlugins } from '@botonic/core'\nimport { Agent, type AgentOutputType, type Handoff } from '@openai/agents'\nimport { RECOMMENDED_PROMPT_PREFIX } from '@openai/agents-core/extensions'\nimport type { z } from 'zod'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport type { OutputSchema } from '../structured-output'\nimport type { AIAgent, Context, GuardrailRule } from '../types'\nimport { BaseAgent } from './base-agent'\n\ninterface RouterAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n name: string\n instructions: string\n llmConfig: LLMConfig\n handoffs: Handoff<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >[]\n inputGuardrailRules: GuardrailRule[]\n outputMessagesSchemas?: z.ZodObject[]\n guardrailTrackingContext: GuardrailTrackingContext\n}\n\nexport class RouterAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseAgent {\n private handoffs: Handoff<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >[]\n private agent!: AIAgent<TPlugins, TExtraData>\n\n private constructor(options: RouterAgentOptions<TPlugins, TExtraData>) {\n super(options)\n this.handoffs = options.handoffs\n }\n\n static async create<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n >(\n options: RouterAgentOptions<TPlugins, TExtraData>\n ): Promise<RouterAgent<TPlugins, TExtraData>> {\n const routerAgent = new RouterAgent<TPlugins, TExtraData>(options)\n const inputGuardrails = await routerAgent.getInputGuardrails()\n\n // Agent.create is typed as Agent<UnknownContext>; we run with Context<TPlugins, TExtraData>.\n const agent = Agent.create({\n name: routerAgent.name,\n model: await routerAgent.getModel(),\n modelSettings: routerAgent.getAgentModelSettings(),\n instructions: routerAgent.addOutputInstructions(\n `${RECOMMENDED_PROMPT_PREFIX}${routerAgent.instructions}`\n ),\n handoffs: routerAgent.handoffs,\n outputType: routerAgent.getOutputType(),\n inputGuardrails,\n }) as AIAgent<TPlugins, TExtraData>\n\n routerAgent.agent = agent\n return routerAgent\n }\n\n getAgent(): AIAgent<TPlugins, TExtraData> {\n return this.agent\n }\n}\n"],"names":["Agent","RECOMMENDED_PROMPT_PREFIX","BaseAgent","RouterAgent","options","routerAgent","inputGuardrails","agent"],"mappings":";;;;;;;;;;;;;;;;;;AAC0E;AACA;AAMlC;AAkBjC,MAAMG,WAAWA,SAGdD,SAASA;IAYjB,aAAa,OAIXE,OAAiD,EACL;QAC5C,MAAMC,cAAc,IAAIF,WAAWA,CAAuBC;QAC1D,MAAME,kBAAkB,MAAMD,YAAY,kBAAkB;QAE5D,6FAA6F;QAC7F,MAAME,QAAQP,YAAY,CAAC;YACzB,MAAMK,YAAY,IAAI;YACtB,OAAO,MAAMA,YAAY,QAAQ;YACjC,eAAeA,YAAY,qBAAqB;YAChD,cAAcA,YAAY,qBAAqB,CAC7C,GAAGJ,yBAAyBA,GAAGI,YAAY,YAAY,EAAE;YAE3D,UAAUA,YAAY,QAAQ;YAC9B,YAAYA,YAAY,aAAa;YACrCC;QACF;QAEAD,YAAY,KAAK,GAAGE;QACpB,OAAOF;IACT;IAEA,WAA0C;QACxC,OAAO,IAAI,CAAC,KAAK;IACnB;IAjCA,YAAoBD,OAAiD,CAAE;QACrE,KAAK,CAACA,UAPR,uBAAQ,YAAR,SAIA,uBAAQ,SAAR;QAIE,IAAI,CAAC,QAAQ,GAAGA,QAAQ,QAAQ;IAClC;AA+BF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"agents/specialist-agent.js","sources":["../../../src/agents/specialist-agent.ts"],"sourcesContent":["import type { CampaignV2, ContactInfo, ResolvedPlugins } from '@botonic/core'\nimport { Agent, type AgentOutputType, type ModelSettings } from '@openai/agents'\nimport type { z } from 'zod'\nimport { LLM_PROVIDER } from '../constants'\nimport type { DebugLogger } from '../debug-logger'\nimport type { GuardrailTrackingContext } from '../guardrails/input'\nimport type { LLMConfig } from '../llm-config'\nimport type { OutputSchema } from '../structured-output'\nimport {\n createRetrieveKnowledge,\n mandatoryTools,\n RETRIEVE_KNOWLEDGE_TOOL_NAME,\n} from '../tools'\nimport type { AIAgent, Context, GuardrailRule, Tool } from '../types'\nimport { BaseAgent } from './base-agent'\n\ninterface SpecialistAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n name: string\n instructions: string\n tools: Tool<TPlugins, TExtraData>[]\n campaignsContext?: CampaignV2[]\n contactInfo: ContactInfo[]\n inputGuardrailRules: GuardrailRule[]\n sourceIds: string[]\n outputMessagesSchemas?: z.ZodObject[]\n llmConfig: LLMConfig\n logger: DebugLogger\n guardrailTrackingContext: GuardrailTrackingContext\n forceToolNameOverride?: string\n disableForceRetrieveKnowledge?: boolean\n}\n\nexport class SpecialistAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseAgent {\n private tools: Tool<TPlugins, TExtraData>[]\n private logger: DebugLogger\n private agent!: AIAgent<TPlugins, TExtraData>\n private forceToolNameOverride?: string\n private disableForceRetrieveKnowledge?: boolean\n\n private constructor(options: SpecialistAgentOptions<TPlugins, TExtraData>) {\n super({\n name: options.name,\n instructions: options.instructions,\n llmConfig: options.llmConfig,\n inputGuardrailRules: options.inputGuardrailRules,\n outputMessagesSchemas: options.outputMessagesSchemas,\n guardrailTrackingContext: options.guardrailTrackingContext,\n })\n this.instructions = this.addExtraInstructions(\n options.instructions,\n options.contactInfo,\n options.campaignsContext\n )\n this.tools = this.addHubtypeTools(options.tools, options.sourceIds)\n this.logger = options.logger\n this.forceToolNameOverride = options.forceToolNameOverride\n this.disableForceRetrieveKnowledge = options.disableForceRetrieveKnowledge\n }\n\n static async create<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n >(\n options: SpecialistAgentOptions<TPlugins, TExtraData>\n ): Promise<SpecialistAgent<TPlugins, TExtraData>> {\n const specialistAgent = new SpecialistAgent<TPlugins, TExtraData>(options)\n const model = specialistAgent.llmConfig.modelName\n const resolvedModel = await specialistAgent.getModel()\n const hasRetrieveKnowledge = specialistAgent.tools.some(\n tool => tool.name === RETRIEVE_KNOWLEDGE_TOOL_NAME\n )\n const modelSettings =\n specialistAgent.getSpecialistModelSettings(hasRetrieveKnowledge)\n const inputGuardrails = await specialistAgent.getInputGuardrails()\n\n specialistAgent.logger.logModelSettings({\n provider: LLM_PROVIDER,\n model,\n reasoning: modelSettings.reasoning as { effort: string } | undefined,\n text: modelSettings.text as { verbosity: string } | undefined,\n toolChoice: modelSettings.toolChoice,\n hasRetrieveKnowledge,\n })\n\n const agent = new Agent<\n Context<TPlugins, TExtraData>,\n AgentOutputType<typeof OutputSchema>\n >({\n name: specialistAgent.name,\n model: resolvedModel,\n modelSettings,\n instructions: specialistAgent.instructions,\n tools: specialistAgent.tools,\n outputType: specialistAgent.getOutputType(),\n inputGuardrails,\n outputGuardrails: [],\n })\n\n specialistAgent.agent = agent\n return specialistAgent\n }\n\n getAgent(): AIAgent<TPlugins, TExtraData> {\n return this.agent\n }\n\n private getSpecialistModelSettings(\n hasRetrieveKnowledge: boolean\n ): ModelSettings {\n const modelSettings = this.getAgentModelSettings()\n const forceRetrieveKnowledge =\n hasRetrieveKnowledge &&\n !this.forceToolNameOverride &&\n !this.disableForceRetrieveKnowledge\n\n if (forceRetrieveKnowledge) {\n modelSettings.toolChoice = RETRIEVE_KNOWLEDGE_TOOL_NAME\n }\n\n if (this.forceToolNameOverride) {\n modelSettings.toolChoice = this.forceToolNameOverride\n }\n\n return modelSettings\n }\n\n private addExtraInstructions(\n initialInstructions: string,\n contactInfo: ContactInfo[],\n campaignsContext?: CampaignV2[]\n ): string {\n const sections = [\n `<instructions>\\n${initialInstructions.trim()}\\n</instructions>`,\n this.getMetadataInstructions(),\n this.getContactInfoInstructions(contactInfo),\n this.getCampaignInstructions(campaignsContext),\n ].filter(section => section.length > 0)\n\n return this.addOutputInstructions(sections.join('\\n\\n'))\n }\n\n private getContactInfoInstructions(contactInfo: ContactInfo[]): string {\n return `<contact_info_fields>${JSON.stringify(\n contactInfo.map(info => ({\n name: info.name,\n value: info.value,\n })),\n null,\n 0\n )}</contact_info_fields>`\n }\n\n private getMetadataInstructions(): string {\n const metadata = `Current Date: ${new Date().toISOString()}`\n return `<metadata>\\n${metadata}\\n</metadata>`\n }\n\n private getCampaignInstructions(campaignsContext?: CampaignV2[]): string {\n if (!campaignsContext || campaignsContext.length === 0) {\n return ''\n }\n const campaignsWithContext = campaignsContext.filter(\n campaign => campaign.agent_context\n )\n if (campaignsWithContext.length === 0) {\n return ''\n }\n return campaignsWithContext\n .map(\n (campaign, index) =>\n `<campaign_context_${index + 1}>\\n${campaign.agent_context}\\n</campaign_context_${index + 1}>`\n )\n .join('\\n')\n }\n\n private addHubtypeTools(\n tools: Tool<TPlugins, TExtraData>[],\n sourceIds: string[]\n ): Tool<TPlugins, TExtraData>[] {\n const hubtypeTools: Tool[] = [...mandatoryTools]\n if (sourceIds.length > 0) {\n hubtypeTools.push(createRetrieveKnowledge(sourceIds))\n }\n return [...hubtypeTools, ...tools]\n }\n}\n"],"names":["Agent","LLM_PROVIDER","createRetrieveKnowledge","mandatoryTools","RETRIEVE_KNOWLEDGE_TOOL_NAME","BaseAgent","SpecialistAgent","options","specialistAgent","model","resolvedModel","hasRetrieveKnowledge","tool","modelSettings","inputGuardrails","agent","forceRetrieveKnowledge","initialInstructions","contactInfo","campaignsContext","sections","section","JSON","info","metadata","Date","campaignsWithContext","campaign","index","tools","sourceIds","hubtypeTools"],"mappings":";;;;;;;;;;;;;;;;;;;;AACgF;AAErC;AAS1B;AAEuB;AAqBjC,MAAMM,eAAeA,SAGlBD,SAASA;IA2BjB,aAAa,OAIXE,OAAqD,EACL;QAChD,MAAMC,kBAAkB,IAAIF,eAAeA,CAAuBC;QAClE,MAAME,QAAQD,gBAAgB,SAAS,CAAC,SAAS;QACjD,MAAME,gBAAgB,MAAMF,gBAAgB,QAAQ;QACpD,MAAMG,uBAAuBH,gBAAgB,KAAK,CAAC,IAAI,CACrDI,CAAAA,OAAQA,KAAK,IAAI,KAAKR,4BAA4BA;QAEpD,MAAMS,gBACJL,gBAAgB,0BAA0B,CAACG;QAC7C,MAAMG,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Q,iCAAR;QAWE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,oBAAoB,CAC3CA,QAAQ,YAAY,EACpBA,QAAQ,WAAW,EACnBA,QAAQ,gBAAgB;QAE1B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,eAAe,CAACA,QAAQ,KAAK,EAAEA,QAAQ,SAAS;QAClE,IAAI,CAAC,MAAM,GAAGA,QAAQ,MAAM;QAC5B,IAAI,CAAC,qBAAqB,GAAGA,QAAQ,qBAAqB;QAC1D,IAAI,CAAC,6BAA6B,GAAGA,QAAQ,6BAA6B;IAC5E;AAgIF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"bot-config-tools.js","sources":["../../src/bot-config-tools.ts"],"sourcesContent":["import type { ToolConfigJSON } from '@botonic/core'\nimport { z } from 'zod'\n\nimport type { CustomTool } from './types'\n\n/**\n * Maps custom AI agent tools to the format expected by bot config (e.g. for flow-builder).\n * Converts each tool's Zod schema to JSON Schema so it can be serialized in the config.\n */\nexport function getToolsForBotConfig(\n customTools: CustomTool[]\n): ToolConfigJSON[] {\n return customTools.map(tool => ({\n name: tool.name,\n description: tool.description,\n schema: z.toJSONSchema(tool.schema, {\n target: 'draft-07',\n }) as ToolConfigJSON['schema'],\n }))\n}\n"],"names":["z","getToolsForBotConfig","customTools","tool"],"mappings":";;;AACuB;AAIvB;;;CAGC,GACM,SAASC,oBAAoBA,CAClCC,WAAyB;IAEzB,OAAOA,YAAY,GAAG,CAACC,CAAAA,OAAS;YAC9B,MAAMA,KAAK,IAAI;YACf,aAAaA,KAAK,WAAW;YAC7B,QAAQH,cAAc,CAACG,KAAK,MAAM,EAAE;gBAClC,QAAQ;YACV;QACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.js","sources":["../../src/constants.ts"],"sourcesContent":["export const HUBTYPE_API_URL =\n process.env.HUBTYPE_API_URL || 'https://api.hubtype.com'\n\n// LLM Configuration (provider-agnostic; set LLM_PROVIDER=azure|openai)\nexport const LLM_PROVIDERS = {\n AZURE: 'azure',\n OPENAI: 'openai',\n LITELLM: 'litellm',\n} as const\n\nexport type LLMProviderType = (typeof LLM_PROVIDERS)[keyof typeof LLM_PROVIDERS]\n\nexport const LITELLM_TAG_KEYS = {\n BOT_ID: 'bot_id',\n ORG_ID: 'org_id',\n SEPARATOR: ',',\n} as const\n\nexport const LLM_PROVIDER: LLMProviderType =\n (process.env.LLM_PROVIDER as LLMProviderType) || LLM_PROVIDERS.AZURE\nexport const LLM_API_KEY = process.env.LLM_API_KEY // pragma: allowlist secret\nexport const LLM_API_URL = process.env.LLM_API_URL\nexport const LLM_AZURE_API_VERSION =\n process.env.LLM_AZURE_API_VERSION || '2025-01-01-preview'\nexport const LLM_OPENAI_MODEL = process.env.LLM_OPENAI_MODEL || 'gpt-4.1-mini'\n\nexport const isProd = process.env.NODE_ENV === 'production'\n\nexport const MAX_MEMORY_LENGTH = 25\n\nexport const DEFAULT_TIMEOUT_16_SECONDS = 16000\nexport const DEFAULT_MAX_RETRIES = 2\n"],"names":["HUBTYPE_API_URL","process","LLM_PROVIDERS","LITELLM_TAG_KEYS","LLM_PROVIDER","LLM_API_KEY","LLM_API_URL","LLM_AZURE_API_VERSION","LLM_OPENAI_MODEL","isProd","MAX_MEMORY_LENGTH","DEFAULT_TIMEOUT_16_SECONDS","DEFAULT_MAX_RETRIES"],"mappings":"AAAO,MAAMA,eAAeA,GAC1BC,QAAQ,GAAG,CAAC,eAAe,IAAI,0BAAyB;AAE1D,uEAAuE;AAChE,MAAMC,aAAaA,GAAG;IAC3B,OAAO;IACP,QAAQ;IACR,SAAS;AACX,EAAU;AAIH,MAAMC,gBAAgBA,GAAG;IAC9B,QAAQ;IACR,QAAQ;IACR,WAAW;AACb,EAAU;AAEH,MAAMC,YAAYA,GACtBH,QAAQ,GAAG,CAAC,YAAY,IAAwBC,aAAaA,CAAC,KAAK;AAC/D,MAAMG,WAAWA,GAAGJ,QAAQ,GAAG,CAAC,WAAW,CAAC,2BAA2B;CAA5B;AAC3C,MAAMK,WAAWA,GAAGL,QAAQ,GAAG,CAAC,WAAW;AAC3C,MAAMM,qBAAqBA,GAChCN,QAAQ,GAAG,CAAC,qBAAqB,IAAI,qBAAoB;AACpD,MAAMO,gBAAgBA,GAAGP,QAAQ,GAAG,CAAC,gBAAgB,IAAI,eAAc;AAEvE,MAAMQ,MAAMA,GAAGR,oBAAoB,KAAK,aAAY;AAEpD,MAAMS,iBAAiBA,GAAG,GAAE;AAE5B,MAAMC,0BAA0BA,GAAG,MAAK;AACxC,MAAMC,mBAAmBA,GAAG,EAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug-logger.js","sources":["../../src/debug-logger.ts"],"sourcesContent":["import {\n type AiAgentArgs,\n AiAgentType,\n type ToolExecution,\n} from '@botonic/core'\nimport type { ModelSettings } from '@openai/agents'\nimport { LLM_PROVIDER } from './constants'\nimport type { AgenticInputMessage, MemoryOptions, RunResult } from './types'\n\nconst PREFIX = '[BotonicPluginAiAgents]'\n\nexport interface DebugLoggerConfig {\n messageHistoryApiVersion: string\n maxRetries: number\n timeout: number\n customToolNames: string[]\n memory: MemoryOptions\n}\n\nexport interface ModelSettingsInfo {\n provider: string\n model: string | undefined\n reasoning?: { effort: string }\n text?: { verbosity: string }\n toolChoice?: string\n hasRetrieveKnowledge: boolean\n}\n\nexport interface DebugLogger {\n logInitialConfig(config: DebugLoggerConfig): void\n logAgentDebugInfo(\n aiAgentArgs: AiAgentArgs,\n toolNames: string[],\n messages: AgenticInputMessage[]\n ): void\n logModelSettings(settings: ModelSettingsInfo): void\n logRunnerStart(\n model: string,\n modelSettings: ModelSettings,\n prompt: string\n ): void\n logRunResult(runResult: RunResult, startTime: number): void\n logGuardrailTriggered(): void\n logRunnerError(startTime: number, error: unknown): void\n logToolExecution(toolExecution: ToolExecution): void\n}\n\nclass EnabledDebugLogger implements DebugLogger {\n logInitialConfig(config: DebugLoggerConfig): void {\n console.log(`${PREFIX} === Plugin Initialization ===`)\n console.log(`${PREFIX} Provider: ${LLM_PROVIDER}`)\n console.log(\n `${PREFIX} Message History API Version: ${config.messageHistoryApiVersion}`\n )\n console.log(`${PREFIX} Max Retries: ${config.maxRetries}`)\n console.log(`${PREFIX} Timeout: ${config.timeout}ms`)\n console.log(\n `${PREFIX} Custom Tools Registered: ${config.customToolNames.join(', ') || 'none'}`\n )\n console.log(`${PREFIX} Memory Options:`, {\n maxMessages: config.memory.maxMessages,\n includeToolCalls: config.memory.includeToolCalls,\n maxFullToolResults: config.memory.maxFullToolResults,\n debugMode: config.memory.debugMode,\n })\n console.log(`${PREFIX} === End Plugin Initialization ===`)\n }\n\n logAgentDebugInfo(\n aiAgentArgs: AiAgentArgs,\n toolNames: string[],\n messages: AgenticInputMessage[]\n ): void {\n console.log(`${PREFIX} === AI Agent Debug Info ===`)\n console.log(`${PREFIX} Agent Name: ${aiAgentArgs.name}`)\n console.log(`${PREFIX} Active Tools: ${JSON.stringify(toolNames)}`)\n if (aiAgentArgs.type === AiAgentType.Specialist) {\n console.log(\n `${PREFIX} Source IDs: ${JSON.stringify(aiAgentArgs.sourceIds || [])}`\n )\n }\n console.log(`${PREFIX} Message History Count: ${messages.length}`)\n console.log(`${PREFIX} Messages: ${JSON.stringify(messages, null, 2)}`)\n console.log(\n `${PREFIX} Input Guardrail Rules: ${aiAgentArgs.inputGuardrailRules?.length || 0}`\n )\n console.log(`${PREFIX} === End Debug Info ===`)\n }\n\n logModelSettings(settings: ModelSettingsInfo): void {\n console.log(`${PREFIX} === Agent Model Settings ===`)\n console.log(\n `${PREFIX} Has Retrieve Knowledge Tool: ${settings.hasRetrieveKnowledge}`\n )\n if (settings.reasoning) {\n console.log(`${PREFIX} Reasoning Effort: ${settings.reasoning.effort}`)\n }\n if (settings.text) {\n console.log(`${PREFIX} Text Verbosity: ${settings.text.verbosity}`)\n }\n if (settings.toolChoice) {\n console.log(`${PREFIX} Tool Choice: ${settings.toolChoice}`)\n }\n console.log(`${PREFIX} === End Model Settings ===`)\n }\n\n logRunnerStart(\n model: string,\n modelSettings: ModelSettings,\n prompt: string\n ): void {\n console.log(`${PREFIX} === Runner Execution Start ===`)\n console.log(`${PREFIX} Model: ${model}`)\n console.log(`${PREFIX} Model Settings: ${JSON.stringify(modelSettings)}`)\n console.log(`${PREFIX} Prompt: ${prompt}`)\n }\n\n logRunResult(runResult: RunResult, startTime: number): void {\n const elapsedMs = Date.now() - startTime\n\n console.log(`${PREFIX} === Runner Execution Complete ===`)\n console.log(`${PREFIX} Execution Time: ${elapsedMs}ms`)\n console.log(`${PREFIX} Output Messages Count: ${runResult.messages.length}`)\n console.log(`${PREFIX} Exit: ${runResult.exit}`)\n console.log(`${PREFIX} Error: ${runResult.error}`)\n console.log(\n `${PREFIX} Tools Executed: ${JSON.stringify(runResult.toolsExecuted.map(t => t.toolName))}`\n )\n if (runResult.inputGuardrailsTriggered.length > 0) {\n console.log(\n `${PREFIX} Input Guardrails Triggered: ${runResult.inputGuardrailsTriggered.length}`\n )\n }\n if (runResult.outputGuardrailsTriggered.length > 0) {\n console.log(\n `${PREFIX} Output Guardrails Triggered: ${runResult.outputGuardrailsTriggered.length}`\n )\n }\n console.log(`${PREFIX} === End Runner Execution ===`)\n }\n\n logGuardrailTriggered(): void {\n console.log(`${PREFIX} Input guardrail triggered`)\n }\n\n logRunnerError(startTime: number, error: unknown): void {\n const elapsedMs = Date.now() - startTime\n console.log(`${PREFIX} Runner execution failed after ${elapsedMs}ms`)\n console.log(`${PREFIX} Error:`, error)\n }\n\n logToolExecution(toolExecution: ToolExecution): void {\n console.log(`${PREFIX} Tool Execution: ${toolExecution.toolName}`)\n console.log(\n `${PREFIX} Tool Arguments: ${JSON.stringify(toolExecution.toolArguments)}`\n )\n console.log(`${PREFIX} Tool Results: ${toolExecution.toolResults}`)\n console.log(\n `${PREFIX} Knowledgebase Sources IDs: ${JSON.stringify(toolExecution.knowledgebaseSourcesIds)}`\n )\n console.log(\n `${PREFIX} Knowledgebase Chunks IDs: ${JSON.stringify(toolExecution.knowledgebaseChunksIds)}`\n )\n }\n}\n\nclass DisabledDebugLogger implements DebugLogger {\n logInitialConfig(): void {\n return\n }\n logAgentDebugInfo(): void {\n return\n }\n logModelSettings(): void {\n return\n }\n logRunnerStart(\n _model: string,\n _modelSettings: ModelSettings,\n _prompt: string\n ): void {\n return\n }\n logRunResult(): void {\n return\n }\n logGuardrailTriggered(): void {\n return\n }\n logRunnerError(): void {\n return\n }\n logToolExecution(): void {\n return\n }\n}\n\nexport function createDebugLogger(enableDebug: boolean): DebugLogger {\n return enableDebug ? new EnabledDebugLogger() : new DisabledDebugLogger()\n}\n"],"names":["AiAgentType","LLM_PROVIDER","PREFIX","EnabledDebugLogger","config","console","aiAgentArgs","toolNames","messages","JSON","settings","model","modelSettings","prompt","runResult","startTime","elapsedMs","Date","t","error","toolExecution","DisabledDebugLogger","_model","_modelSettings","_prompt","createDebugLogger","enableDebug"],"mappings":";;;;;AAIsB;AAEoB;AAG1C,MAAME,MAAMA,GAAG;AAsCf,MAAMC,kBAAkBA;IACtB,iBAAiBC,MAAyB,EAAQ;QAChDC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,8BAA8B,CAAC;QACrDG,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,WAAW,EAAED,YAAYA,EAAE;QACjDI,QAAQ,GAAG,CACT,GAAGH,MAAMA,CAAC,8BAA8B,EAAEE,OAAO,wBAAwB,EAAE;QAE7EC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,cAAc,EAAEE,OAAO,UAAU,EAAE;QACzDC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,UAAU,EAAEE,OAAO,OAAO,CAAC,EAAE,CAAC;QACpDC,QAAQ,GAAG,CACT,GAAGH,MAAMA,CAAC,0BAA0B,EAAEE,OAAO,eAAe,CAAC,IAAI,CAAC,SAAS,QAAQ;QAErFC,QAAQ,GAAG,CAAC,GAAGH,MAAMA,CAAC,gBAAgB,CAAC,EAAE;YACvC,aAAaE,OA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MA,CAAC,2BAA2B,EAAEO,KAAK,SAAS,CAACW,cAAc,sBAAsB,GAAG;IAEjG;AACF;AAEA,MAAMC,mBAAmBA;IACvB,mBAAyB;QACvB;IACF;IACA,oBAA0B;QACxB;IACF;IACA,mBAAyB;QACvB;IACF;IACA,eACEC,MAAc,EACdC,cAA6B,EAC7BC,OAAe,EACT;QACN;IACF;IACA,eAAqB;QACnB;IACF;IACA,wBAA8B;QAC5B;IACF;IACA,iBAAuB;QACrB;IACF;IACA,mBAAyB;QACvB;IACF;AACF;AAEO,SAASC,iBAAiBA,CAACC,WAAoB;IACpD,OAAOA,cAAc,IAAIvB,kBAAkBA,KAAK,IAAIkB,mBAAmBA;AACzE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"guardrails/index.js","sources":["../../../src/guardrails/index.ts"],"sourcesContent":["export * from './input'\n"],"names":[],"mappings":";AAAuB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"guardrails/input.js","sources":["../../../src/guardrails/input.ts"],"sourcesContent":["import {\n Agent,\n type InputGuardrail,\n type ModelSettings,\n Runner,\n type UserMessageItem,\n} from '@openai/agents'\nimport { z } from 'zod'\nimport { isProd, LLM_PROVIDERS } from '../constants'\nimport type { LLMConfig } from '../llm-config'\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport { TrackFeature, TrackProductName } from '../services/types'\nimport type { GuardrailRule, ResultRawResponse } from '../types'\n\nexport interface GuardrailTrackingContext {\n botId: string\n isTest: boolean\n authToken: string\n inferenceId: string\n}\n\nexport async function createInputGuardrails(\n rules: GuardrailRule[],\n llmConfig: LLMConfig,\n trackingContext: GuardrailTrackingContext\n): Promise<InputGuardrail[]> {\n if (rules.length === 0) {\n return []\n }\n\n return [await buildInputGuardrail(rules, llmConfig, trackingContext)]\n}\n\nasync function buildInputGuardrail(\n rules: GuardrailRule[],\n llmConfig: LLMConfig,\n trackingContext: GuardrailTrackingContext\n): Promise<InputGuardrail> {\n const outputType = z.object(\n Object.fromEntries(\n rules.map(rule => [rule.name, z.boolean().describe(rule.description)])\n )\n )\n const modelSettings = createInputGuardrailModelSettings(llmConfig)\n\n const agent = new Agent({\n name: 'InputGuardrail',\n model: await llmConfig.getModel(),\n modelSettings,\n instructions:\n 'Check if the user triggers some of the following guardrails.',\n outputType,\n })\n\n return {\n name: 'InputGuardrail',\n execute: async ({ input, context }) => {\n const lastMessage = input[input.length - 1] as UserMessageItem\n const runner = new Runner({\n tracingDisabled: true,\n })\n const startTime = Date.now()\n const result = await runner.run(agent, [lastMessage], { context })\n const endTime = Date.now()\n\n await sendGuardrailLlmRunTracking(\n result,\n trackingContext,\n llmConfig,\n startTime,\n endTime\n )\n\n const finalOutput = result.finalOutput as Record<string, boolean>\n if (finalOutput === undefined) {\n throw new Error('Guardrail agent failed to produce output')\n }\n const triggered = Object.values(finalOutput).some(value => value === true)\n const triggeredGuardrails = Object.keys(finalOutput).filter(\n key => finalOutput[key] === true\n )\n return {\n outputInfo: triggeredGuardrails,\n tripwireTriggered: triggered,\n }\n },\n }\n}\n\nfunction createInputGuardrailModelSettings(\n llmConfig: LLMConfig\n): ModelSettings {\n const modelSettings: ModelSettings = {\n ...llmConfig.modelSettings,\n toolChoice: undefined,\n }\n if (llmConfig.modelSettings.reasoning) {\n modelSettings.reasoning = { ...llmConfig.modelSettings.reasoning }\n }\n if (llmConfig.modelSettings.text) {\n modelSettings.text = { ...llmConfig.modelSettings.text }\n }\n return modelSettings\n}\n\nasync function sendGuardrailLlmRunTracking(\n result: {\n rawResponses?: ResultRawResponse[]\n },\n trackingContext: GuardrailTrackingContext,\n llmConfig: LLMConfig,\n startTime: number,\n endTime: number\n): Promise<void> {\n if (!isProd) {\n return\n }\n if (llmConfig.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return\n }\n const rawResponses = result.rawResponses ?? []\n if (rawResponses.length === 0) {\n return\n }\n const totalDuration = endTime - startTime\n const durationPerCall = Math.round(totalDuration / rawResponses.length)\n const temperature =\n (llmConfig.modelSettings.temperature as number | undefined) ?? 0\n const llmRuns = rawResponses.map(response => ({\n inference_id: trackingContext.inferenceId,\n is_test: trackingContext.isTest,\n product_name: TrackProductName.AI_AGENT,\n deployment_name: llmConfig.modelName,\n model_name:\n (response.providerData?.model as string | undefined) ??\n llmConfig.modelName,\n feature: TrackFeature.AI_AGENT_GUARDRAIL,\n api_version: llmConfig.getApiVersion(),\n num_prompt_tokens: response.usage.inputTokens,\n num_completion_tokens: response.usage.outputTokens,\n duration_in_milliseconds: durationPerCall,\n temperature,\n error: null,\n }))\n\n const client = new HubtypeApiClient(trackingContext.authToken)\n await client.trackLlmRuns(trackingContext.botId, {\n llm_runs: llmRuns,\n })\n}\n"],"names":["Agent","Runner","z","isProd","LLM_PROVIDERS","HubtypeApiClient","TrackFeature","TrackProductName","createInputGuardrails","rules","llmConfig","trackingContext","buildInputGuardrail","outputType","Object","rule","modelSettings","createInputGuardrailModelSettings","agent","input","context","lastMessage","runner","startTime","Date","result","endTime","sendGuardrailLlmRunTracking","finalOutput","undefined","Error","triggered","value","triggeredGuardrails","key","rawResponses","totalDuration","durationPerCall","Math","temperature","llmRuns","response","client"],"mappings":";;;;;;;;;;;AAMuB;AACA;AAC6B;AAEa;AACC;AAU3D,eAAeQ,qBAAqBA,CACzCC,KAAsB,EACtBC,SAAoB,EACpBC,eAAyC;IAEzC,IAAIF,MAAM,MAAM,KAAK,GAAG;QACtB,OAAO,EAAE;IACX;IAEA,OAAO;QAAC,MAAMG,mBAAmBA,CAACH,OAAOC,WAAWC;KAAiB;AACvE;AAEA,eAAeC,mBAAmBA,CAChCH,KAAsB,EACtBC,SAAoB,EACpBC,eAAyC;IAEzC,MAAME,aAAaX,QAAQ,CACzBY,OAAO,WAAW,CAChBL,MAAM,GAAG,CAACM,CAAAA,OAAQ;YAACA,KAAK,IAAI;YAAEb,SAAS,GAAG,QAAQ,CAACa,KAAK,WAAW;SAAE;IAGzE,MAAMC,gBAAgBC,iCAAiCA,CAACP;IAExD,MAAMQ,QAAQ,IAAIl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SAAoB,EACpBa,SAAiB,EACjBG,OAAe;IAEf,IAAI,CAACvB,MAAMA,EAAE;QACX;IACF;IACA,IAAIO,UAAU,eAAe,OAAON,qBAAqB,EAAE;QACzD;IACF;IACA,MAAM+B,eAAeV,OAAO,YAAY,IAAI,EAAE;IAC9C,IAAIU,aAAa,MAAM,KAAK,GAAG;QAC7B;IACF;IACA,MAAMC,gBAAgBV,UAAUH;IAChC,MAAMc,kBAAkBC,KAAK,KAAK,CAACF,gBAAgBD,aAAa,MAAM;IACtE,MAAMI,cACH7B,UAAU,aAAa,CAAC,WAAW,IAA2B;IACjE,MAAM8B,UAAUL,aAAa,GAAG,CAACM,CAAAA,WAAa;YAC5C,cAAc9B,gBAAgB,WAAW;YACzC,SAASA,gBAAgB,MAAM;YAC/B,cAAcJ,yBAAyB;YACvC,iBAAiBG,UAAU,SAAS;YACpC,YACG+B,SAAS,YAAY,EAAE,SACxB/B,UAAU,SAAS;YACrB,SAASJ,+BAA+B;YACxC,aAAaI,UAAU,aAAa;YACpC,mBAAmB+B,SAAS,KAAK,CAAC,WAAW;YAC7C,uBAAuBA,SAAS,KAAK,CAAC,YAAY;YAClD,0BAA0BJ;YAC1BE;YACA,OAAO;QACT;IAEA,MAAMG,SAAS,IAAIrC,gBAAgBA,CAACM,gBAAgB,SAAS;IAC7D,MAAM+B,OAAO,YAAY,CAAC/B,gBAAgB,KAAK,EAAE;QAC/C,UAAU6B;IACZ;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["import {\n type AIAgentRouterArgs,\n type AiAgentArgs,\n type AiAgentSpecialistArgs,\n AiAgentType,\n type BotContext,\n type HubtypeAssistantMessage,\n type Plugin,\n type ResolvedPlugins,\n} from '@botonic/core'\nimport { handoff, setTracingDisabled, tool } from '@openai/agents'\nimport { v7 as uuidv7 } from 'uuid'\nimport type { ZodObject } from 'zod'\nimport { RouterAgent, SpecialistAgent } from './agents'\nimport {\n DEFAULT_MAX_RETRIES,\n DEFAULT_TIMEOUT_16_SECONDS,\n isProd,\n MAX_MEMORY_LENGTH,\n} from './constants'\nimport { createDebugLogger, type DebugLogger } from './debug-logger'\nimport { LLMConfig } from './llm-config'\nimport { RouterRunner, SpecialistRunner } from './runners'\nimport { HubtypeApiClient } from './services/hubtype-api-client'\nimport type {\n AgenticInputMessage,\n Context,\n CustomTool,\n InferenceResponse,\n MemoryOptions,\n PluginAiAgentOptions,\n Tool,\n} from './types'\n\nexport default class BotonicPluginAiAgents<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> implements Plugin\n{\n private readonly authToken?: string\n private readonly memory: MemoryOptions\n private readonly logger: DebugLogger\n private readonly timeout: number\n private readonly maxRetries: number\n public toolDefinitions: CustomTool<TPlugins, TExtraData>[] = []\n private readonly localStorageKey: string\n\n constructor(options?: PluginAiAgentOptions<TPlugins, TExtraData>) {\n this.authToken = options?.authToken\n this.toolDefinitions = options?.customTools || []\n this.memory = this.getMemoryOptions(options?.memory)\n this.timeout = options?.timeout ?? DEFAULT_TIMEOUT_16_SECONDS\n this.maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES\n this.logger = createDebugLogger(options?.enableDebug ?? false)\n this.localStorageKey = options?.localStorageKey ?? 'botonicState'\n setTracingDisabled(true)\n\n this.logger.logInitialConfig({\n messageHistoryApiVersion: 'v2',\n maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_16_SECONDS,\n customToolNames: this.toolDefinitions.map(t => t.name),\n memory: this.memory,\n })\n }\n\n private getMemoryOptions(memory?: Partial<MemoryOptions>): MemoryOptions {\n return {\n maxMessages: memory?.maxMessages ?? MAX_MEMORY_LENGTH,\n includeToolCalls: memory?.includeToolCalls ?? true,\n maxFullToolResults: memory?.maxFullToolResults ?? 1,\n debugMode: memory?.debugMode ?? false,\n }\n }\n\n pre(): void {\n return\n }\n\n async getInference(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AiAgentArgs\n ): Promise<InferenceResponse> {\n const authToken = isProd ? botContext.session._access_token : this.authToken\n if (!authToken) {\n throw new Error('Auth token is required')\n }\n\n const inferenceId = uuidv7()\n\n try {\n if (aiAgentArgs.type === AiAgentType.Specialist) {\n return await this.executeSpecialistAIAgent(\n botContext,\n aiAgentArgs,\n authToken,\n inferenceId\n )\n }\n\n if (aiAgentArgs.type === AiAgentType.Router) {\n return await this.executeRouterAIAgent(\n botContext,\n aiAgentArgs,\n authToken,\n inferenceId\n )\n }\n\n throw new Error('Invalid agent type')\n } catch (error) {\n console.error('error plugin returns undefined', error)\n return {\n messages: [],\n toolsExecuted: [],\n memoryLength: 0,\n exit: true,\n error: true,\n inputGuardrailsTriggered: [],\n outputGuardrailsTriggered: [],\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n }\n }\n }\n\n private async executeSpecialistAIAgent(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AiAgentSpecialistArgs,\n authToken: string,\n inferenceId: string\n ) {\n const llmConfig = new LLMConfig({\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n modelName: aiAgentArgs.model,\n verbosity: aiAgentArgs.verbosity,\n botContext,\n reasoningEffort: aiAgentArgs.reasoningEffort,\n })\n\n // Get LLM config, tools and agent\n const { tools, agent } = await this.getSpecialistAgentAndTools(\n botContext,\n aiAgentArgs,\n aiAgentArgs.outputMessagesSchemas || [],\n authToken,\n inferenceId,\n llmConfig\n )\n\n // Get messages\n const messages = await this.getMessages(\n botContext,\n authToken,\n aiAgentArgs.previousHubtypeMessages || []\n )\n\n // Build context\n const context: Context<TPlugins, TExtraData> = {\n authToken,\n knowledgeUsed: {\n query: '',\n sourceIds: [],\n chunksIds: [],\n chunkTexts: [],\n },\n request: botContext,\n }\n\n // Log agent debug info\n this.logger.logAgentDebugInfo(\n aiAgentArgs,\n tools.map(t => t.name),\n messages\n )\n\n // Run agent\n const runner = new SpecialistRunner<TPlugins, TExtraData>(\n agent,\n llmConfig,\n inferenceId,\n this.logger\n )\n return await runner.run(messages, context)\n }\n\n private async executeRouterAIAgent(\n botContext: BotContext<TPlugins, TExtraData>,\n aiAgentArgs: AIAgentRouterArgs,\n authToken: string,\n inferenceId: string\n ) {\n const { specialists, name, instructions } = aiAgentArgs\n\n const llmConfig = new LLMConfig({\n maxRetries: this.maxRetries,\n timeout: this.timeout,\n modelName: aiAgentArgs.model,\n verbosity: aiAgentArgs.verbosity,\n botContext,\n reasoningEffort: aiAgentArgs.reasoningEffort,\n })\n\n const specialistsAgents = await Promise.all(\n specialists.map(async specialistData => {\n // If the forceToolNameOverride is set, we force this override for all specialists\n const forceToolNameOverride = aiAgentArgs.forceToolNameOverride\n const reasoningEffort = aiAgentArgs.reasoningEffort\n const disableForceRetrieveKnowledge =\n aiAgentArgs.disableForceRetrieveKnowledge\n\n // Create AiAgentArgs for the specialist, with values from AIAgentRouterArgs\n const aiAgentSpecialistArgs: AiAgentArgs = {\n ...specialistData,\n forceToolNameOverride,\n reasoningEffort,\n disableForceRetrieveKnowledge,\n }\n\n const { agent } = await this.getSpecialistAgentAndTools(\n botContext,\n aiAgentSpecialistArgs,\n aiAgentArgs.outputMessagesSchemas || [],\n authToken,\n inferenceId,\n llmConfig\n )\n\n return handoff(agent, {\n toolNameOverride: specialistData.name,\n toolDescriptionOverride: specialistData.description,\n })\n })\n )\n\n const router = await RouterAgent.create<TPlugins, TExtraData>({\n name,\n instructions,\n llmConfig,\n handoffs: specialistsAgents,\n inputGuardrailRules: aiAgentArgs.inputGuardrailRules || [],\n outputMessagesSchemas: aiAgentArgs.outputMessagesSchemas || [],\n guardrailTrackingContext: {\n botId: botContext.session.bot.id,\n isTest: botContext.session.is_test_integration,\n authToken,\n inferenceId,\n },\n })\n\n // Get messages\n const messages = await this.getMessages(\n botContext,\n authToken,\n aiAgentArgs.previousHubtypeMessages || []\n )\n\n // Build context\n const context: Context<TPlugins, TExtraData> = {\n authToken,\n knowledgeUsed: {\n query: '',\n sourceIds: [],\n chunksIds: [],\n chunkTexts: [],\n },\n request: botContext,\n }\n\n // Run agent\n const routerAgent = router.getAgent()\n const runner = new RouterRunner<TPlugins, TExtraData>(\n routerAgent,\n llmConfig,\n inferenceId,\n this.logger\n )\n\n return await runner.run(messages, context)\n }\n\n private async getSpecialistAgentAndTools(\n botContext: BotContext,\n aiAgentArgs: AiAgentArgs,\n outputMessagesSchemas: ZodObject<any>[],\n authToken: string,\n inferenceId: string,\n llmConfig: LLMConfig\n ) {\n // Build tools\n const tools = this.buildTools(aiAgentArgs)\n\n // Build agent\n const sourceIds =\n aiAgentArgs.type === AiAgentType.Specialist ? aiAgentArgs.sourceIds : []\n\n const specialist = await SpecialistAgent.create<TPlugins, TExtraData>({\n name: aiAgentArgs.name,\n instructions: aiAgentArgs.instructions,\n tools: tools,\n contactInfo: botContext.session.user.contact_info || [],\n inputGuardrailRules: aiAgentArgs.inputGuardrailRules || [],\n sourceIds,\n outputMessagesSchemas: outputMessagesSchemas || [],\n campaignsContext: botContext.input.context?.campaigns_v2,\n logger: this.logger,\n llmConfig,\n guardrailTrackingContext: {\n botId: botContext.session.bot.id,\n isTest: botContext.session.is_test_integration,\n authToken,\n inferenceId,\n },\n forceToolNameOverride: aiAgentArgs.forceToolNameOverride,\n disableForceRetrieveKnowledge: aiAgentArgs.disableForceRetrieveKnowledge,\n })\n const specialistAgent = specialist.getAgent()\n\n return { agent: specialistAgent, tools }\n }\n\n private async getMessages(\n botContext: BotContext,\n authToken: string,\n previousHubtypeMessages: HubtypeAssistantMessage[]\n ): Promise<AgenticInputMessage[]> {\n const hubtypeClient = new HubtypeApiClient(authToken)\n if (!isProd) {\n return await hubtypeClient.getLocalMessages(\n MAX_MEMORY_LENGTH,\n previousHubtypeMessages,\n this.localStorageKey\n )\n }\n\n // Default to V2\n const result = await hubtypeClient.getMessagesV2(\n botContext,\n this.memory,\n previousHubtypeMessages\n )\n return result.messages\n }\n\n private buildTools(aiAgentArgs: AiAgentArgs): Tool<TPlugins, TExtraData>[] {\n const activeTools =\n aiAgentArgs.type === AiAgentType.Router ? [] : aiAgentArgs.activeTools\n const activeToolNames = activeTools.map(tool => tool.name)\n const availableTools = this.toolDefinitions.filter(tool =>\n activeToolNames.includes(tool.name)\n )\n return availableTools.map(toolDefinition => {\n return tool<any, Context<TPlugins, TExtraData>, any>({\n name: toolDefinition.name,\n description: toolDefinition.description,\n parameters: toolDefinition.schema,\n execute: toolDefinition.func,\n })\n })\n }\n}\n\nexport * from './bot-config-tools'\nexport * from './types'\n"],"names":["AiAgentType","handoff","setTracingDisabled","tool","v7","uuidv7","RouterAgent","SpecialistAgent","DEFAULT_MAX_RETRIES","DEFAULT_TIMEOUT_16_SECONDS","isProd","MAX_MEMORY_LENGTH","createDebugLogger","LLMConfig","RouterRunner","SpecialistRunner","HubtypeApiClient","BotonicPluginAiAgents","memory","botContext","aiAgentArgs","authToken","Error","inferenceId","error","console","llmConfig","tools","agent","messages","context","t","runner","specialists","name","instructions","specialistsAgents","Promise","specialistData","forceToolNameOverride","reasoningEffort","disableForceRetrieveKnowledge","aiAgentSpecialistArgs","router","routerAgent","outputMessagesSchemas","sourceIds","specialist","specialistAgent","previousHubtypeMessages","hubtypeClient","result","activeTools","activeToolNames","availableTools","toolDefinition","options"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASsB;AAC4C;AAC/B;AAEoB;AAMnC;AACgD;AAC5B;AACkB;AACM;AAWjD,MAAMiB,qBAAqBA;IAgChC,iBAAiBC,MAA+B,EAAiB;QACvE,OAAO;YACL,aAAaA,QAAQ,eAAeP,iBAAiBA;YACrD,kBAAkBO,QAAQ,oBAAoB;YAC9C,oBAAoBA,QAAQ,sBAAsB;YAClD,WAAWA,QAAQ,aAAa;QAClC;IACF;IAEA,MAAY;QACV;IACF;IAEA,MAAM,aACJC,UAA4C,EAC5CC,WAAwB,EACI;QAC5B,MAAMC,YAAYX,MAAMA,GAAGS,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,OAAoD,CAAE;QARlE,uBAAiB,aAAjB;QACA,uBAAiB,UAAjB;QACA,uBAAiB,UAAjB;QACA,uBAAiB,WAAjB;QACA,uBAAiB,cAAjB;QACA,uBAAO,mBAAsD,EAAE;QAC/D,uBAAiB,mBAAjB;QAGE,IAAI,CAAC,SAAS,GAAGA,SAAS;QAC1B,IAAI,CAAC,eAAe,GAAGA,SAAS,eAAe,EAAE;QACjD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,gBAAgB,CAACA,SAAS;QAC7C,IAAI,CAAC,OAAO,GAAGA,SAAS,WAAW/C,0BAA0BA;QAC7D,IAAI,CAAC,UAAU,GAAG+C,SAAS,cAAchD,mBAAmBA;QAC5D,IAAI,CAAC,MAAM,GAAGI,iBAAiBA,CAAC4C,SAAS,eAAe;QACxD,IAAI,CAAC,eAAe,GAAGA,SAAS,mBAAmB;QACnDtD,kBAAkBA,CAAC;QAEnB,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC;YAC3B,0BAA0B;YAC1B,YAAYsD,SAAS,cAAchD,mBAAmBA;YACtD,SAASgD,SAAS,WAAW/C,0BAA0BA;YACvD,iBAAiB,IAAI,CAAC,eAAe,CAAC,GAAG,CAACsB,CAAAA,IAAKA,EAAE,IAAI;YACrD,QAAQ,IAAI,CAAC,MAAM;QACrB;IACF;AA2SF;AAAC;AAEiC;AACX"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"llm-config.js","sources":["../../src/llm-config.ts"],"sourcesContent":["import {\n type BotContext,\n type ReasoningEffort,\n VerbosityLevel,\n} from '@botonic/core'\nimport {\n type Model,\n type ModelProvider,\n type ModelSettings,\n OpenAIProvider,\n} from '@openai/agents'\nimport OpenAI, { AzureOpenAI } from 'openai'\nimport {\n isProd,\n LITELLM_TAG_KEYS,\n LLM_API_KEY,\n LLM_API_URL,\n LLM_AZURE_API_VERSION,\n LLM_OPENAI_MODEL,\n LLM_PROVIDER,\n LLM_PROVIDERS,\n type LLMProviderType,\n} from './constants'\n\nexport interface LLMConfigParams {\n maxRetries: number\n timeout: number\n modelName: string\n verbosity: VerbosityLevel\n botContext: BotContext\n reasoningEffort?: ReasoningEffort\n}\n\nexport class LLMConfig {\n private readonly maxRetries: number\n private readonly timeout: number\n private readonly botContext: BotContext\n public readonly modelName: string\n public readonly modelSettings: ModelSettings\n public readonly modelProvider: ModelProvider\n\n constructor({\n maxRetries,\n timeout,\n modelName,\n verbosity,\n botContext,\n reasoningEffort,\n }: LLMConfigParams) {\n this.maxRetries = maxRetries\n this.timeout = timeout\n this.botContext = botContext\n this.modelName =\n LLM_PROVIDER === LLM_PROVIDERS.OPENAI ? LLM_OPENAI_MODEL : modelName\n this.modelProvider = this.getModelProvider()\n this.modelSettings = this.getModelSettings(\n modelName,\n verbosity,\n reasoningEffort\n )\n }\n\n async getModel(): Promise<Model> {\n return await this.modelProvider.getModel(this.modelName)\n }\n\n private getModelProvider(): ModelProvider {\n const client = this.getClient()\n return new OpenAIProvider({\n openAIClient: client,\n useResponses: false,\n })\n }\n\n getProviderName(): LLMProviderType {\n if (\n this.botContext.settings.LITELLM_API_URL ||\n LLM_PROVIDER === LLM_PROVIDERS.LITELLM\n ) {\n return LLM_PROVIDERS.LITELLM\n }\n return LLM_PROVIDER\n }\n\n private getClient(): OpenAI | AzureOpenAI {\n if (this.getProviderName() === LLM_PROVIDERS.LITELLM) {\n const litellmUrl =\n this.botContext.settings.LITELLM_API_URL || LLM_API_URL || ''\n return this.getLiteLLMClient(litellmUrl)\n }\n if (LLM_PROVIDER === LLM_PROVIDERS.OPENAI) {\n return this.getOpenAIClient()\n }\n return this.getAzureOpenAiClient()\n }\n\n private buildLiteLLMTags(): { 'x-litellm-tags': string } | undefined {\n const botId = this.botContext.session.bot.id\n const orgId = this.botContext.session.organization_id\n const parts: string[] = []\n if (botId) {\n parts.push(`${LITELLM_TAG_KEYS.BOT_ID}:${botId}`)\n }\n if (orgId) {\n parts.push(`${LITELLM_TAG_KEYS.ORG_ID}:${orgId}`)\n }\n return parts.length > 0\n ? { 'x-litellm-tags': parts.join(LITELLM_TAG_KEYS.SEPARATOR) }\n : undefined\n }\n\n private getLiteLLMClient(litellmUrl: string): OpenAI {\n return new OpenAI({\n apiKey: this.botContext.secrets.LITELLM_API_KEY || LLM_API_KEY,\n baseURL: litellmUrl,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n defaultHeaders: this.buildLiteLLMTags(),\n })\n }\n\n private getOpenAIClient(): OpenAI {\n return new OpenAI({\n apiKey: this.botContext.secrets.AZURE_OPENAI_API_KEY || LLM_API_KEY,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n })\n }\n\n private getAzureOpenAiClient(): AzureOpenAI {\n const baseURL = `${this.botContext.settings.AZURE_OPENAI_API_BASE || LLM_API_URL}openai/`\n\n return new AzureOpenAI({\n apiKey: this.botContext.secrets.AZURE_OPENAI_API_KEY || LLM_API_KEY,\n apiVersion:\n this.botContext.settings.AZURE_OPENAI_API_VERSION ||\n LLM_AZURE_API_VERSION,\n deployment: this.modelName,\n baseURL,\n timeout: this.timeout,\n maxRetries: this.maxRetries,\n dangerouslyAllowBrowser: !isProd,\n })\n }\n\n private getModelSettings(\n model: string,\n verbosity: VerbosityLevel,\n reasoningEffort?: ReasoningEffort\n ): ModelSettings {\n if (model.includes('gpt-4')) {\n return {\n temperature: 0,\n text: { verbosity: VerbosityLevel.Medium },\n }\n }\n\n if (reasoningEffort) {\n return {\n reasoning: { effort: reasoningEffort },\n temperature: 1,\n text: { verbosity },\n }\n }\n\n return {\n temperature: 1,\n text: { verbosity },\n }\n }\n\n getApiVersion(): string | undefined {\n if (this.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return undefined\n }\n if (LLM_PROVIDER !== LLM_PROVIDERS.AZURE) {\n return 'NOT_API_VERSION_FOR_OPENAI_PROVIDER'\n }\n return (\n this.botContext.settings.AZURE_OPENAI_API_VERSION || LLM_AZURE_API_VERSION\n )\n }\n}\n"],"names":["VerbosityLevel","OpenAIProvider","OpenAI","AzureOpenAI","isProd","LITELLM_TAG_KEYS","LLM_API_KEY","LLM_API_URL","LLM_AZURE_API_VERSION","LLM_OPENAI_MODEL","LLM_PROVIDER","LLM_PROVIDERS","LLMConfig","client","litellmUrl","botId","orgId","parts","undefined","baseURL","model","verbosity","reasoningEffort","maxRetries","timeout","modelName","botContext"],"mappings":";;;;;;;;;;;;;;;;;;;;AAIsB;AAMC;AACqB;AAWxB;AAWb,MAAMY,SAASA;IA6BpB,MAAM,WAA2B;QAC/B,OAAO,MAAM,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS;IACzD;IAEQ,mBAAkC;QACxC,MAAMC,SAAS,IAAI,CAAC,SAAS;QAC7B,OAAO,IAAIZ,cAAcA,CAAC;YACxB,cAAcY;YACd,cAAc;QAChB;IACF;IAEA,kBAAmC;QACjC,IACE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,eAAe,IACxCH,YAAYA,KAAKC,qBAAqB,EACtC;YACA,OAAOA,qBAAqB;QAC9B;QACA,OAAOD,YAAYA;IACrB;IAEQ,YAAkC;QACxC,IAAI,IAAI,CAAC,eAAe,OAAOC,qBAAqB,EAAE;YACpD,MAAMG,aACJ,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,eAAe,IAAIP,WAAWA,IAAI;YAC7D,OAAO,IAAI,CAAC,gBAAgB,CAACO;QAC/B;QACA,IAAIJ,YAAYA,KAAKC,oBAAoB,EAAE;YACzC,OAAO,IAAI,CAAC,eAAe;QAC7B;QACA,OAAO,IAAI,CAAC,oBAAoB;IAClC;IAEQ,mBAA6D;QACnE,MAAMI,QAAQ,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QAC5C,MAAMC,QAAQ,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,eAAe;QACrD,MAAMC,QAAkB,EAAE;QAC1B,IAAIF,OAAO;YACTE,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zBC,eAAiC,EAClB;QACf,IAAIF,MAAM,QAAQ,CAAC,UAAU;YAC3B,OAAO;gBACL,aAAa;gBACb,MAAM;oBAAE,WAAWpB,qBAAqB;gBAAC;YAC3C;QACF;QAEA,IAAIsB,iBAAiB;YACnB,OAAO;gBACL,WAAW;oBAAE,QAAQA;gBAAgB;gBACrC,aAAa;gBACb,MAAM;oBAAED;gBAAU;YACpB;QACF;QAEA,OAAO;YACL,aAAa;YACb,MAAM;gBAAEA;YAAU;QACpB;IACF;IAEA,gBAAoC;QAClC,IAAI,IAAI,CAAC,eAAe,OAAOV,qBAAqB,EAAE;YACpD,OAAOO;QACT;QACA,IAAIR,YAAYA,KAAKC,mBAAmB,EAAE;YACxC,OAAO;QACT;QACA,OACE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,wBAAwB,IAAIH,qBAAqBA;IAE9E;IA9IA,YAAY,EACVe,UAAU,EACVC,OAAO,EACPC,SAAS,EACTJ,SAAS,EACTK,UAAU,EACVJ,eAAe,EACC,CAAE;QAdpB,uBAAiB,cAAjB;QACA,uBAAiB,WAAjB;QACA,uBAAiB,cAAjB;QACA,uBAAgB,aAAhB;QACA,uBAAgB,iBAAhB;QACA,uBAAgB,iBAAhB;QAUE,IAAI,CAAC,UAAU,GAAGC;QAClB,IAAI,CAAC,OAAO,GAAGC;QACf,IAAI,CAAC,UAAU,GAAGE;QAClB,IAAI,CAAC,SAAS,GACZhB,YAAYA,KAAKC,oBAAoB,GAAGF,gBAAgBA,GAAGgB;QAC7D,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB;QAC1C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CACxCA,WACAJ,WACAC;IAEJ;AA4HF"}
@@ -1,3 +0,0 @@
1
- {
2
- "type": "module"
3
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"runners/base-runner.js","sources":["../../../src/runners/base-runner.ts"],"sourcesContent":["import type {\n OutputMessage,\n ResolvedPlugins,\n ToolExecution,\n} from '@botonic/core'\nimport {\n InputGuardrailTripwireTriggered,\n RunContext,\n Runner,\n RunToolCallItem,\n RunToolCallOutputItem,\n} from '@openai/agents'\nimport { isProd, LLM_PROVIDERS } from '../constants'\nimport type { DebugLogger } from '../debug-logger'\nimport type { LLMConfig } from '../llm-config'\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport { TrackFeature, TrackProductName } from '../services/types'\nimport { RETRIEVE_KNOWLEDGE_TOOL_NAME } from '../tools'\nimport type {\n AgenticInputMessage,\n AgenticOutputMessage,\n AIAgent,\n Context,\n ResultRawResponse,\n RunResult,\n} from '../types'\n\n// Minimal interface matching the properties we actually use from Runner.run() result.\n// This bypasses strict type checking while maintaining type safety for accessed properties.\nexport interface RunnerResult {\n finalOutput?: {\n messages?: OutputMessage[]\n }\n rawResponses?: ResultRawResponse[]\n newItems?: unknown[]\n lastAgent?: { name?: string }\n // biome-ignore lint/suspicious/noExplicitAny: state is a complex internal type\n state?: any\n}\n\nexport abstract class BaseRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> {\n protected agent: AIAgent<TPlugins, TExtraData>\n protected llmConfig: LLMConfig\n protected inferenceId: string\n protected logger: DebugLogger\n\n constructor(\n agent: AIAgent<TPlugins, TExtraData>,\n llmConfig: LLMConfig,\n inferenceId: string,\n logger: DebugLogger\n ) {\n this.agent = agent\n this.llmConfig = llmConfig\n this.inferenceId = inferenceId\n this.logger = logger\n }\n\n async run(\n messages: AgenticInputMessage[],\n context: Context<TPlugins, TExtraData>\n ): Promise<RunResult> {\n const startTime = Date.now()\n\n const runContext = new RunContext(context)\n const prompt = (await this.agent.getSystemPrompt(runContext)) ?? ''\n this.logger.logRunnerStart(\n this.llmConfig.modelName,\n this.llmConfig.modelSettings,\n prompt\n )\n\n try {\n const runner = new Runner({\n tracingDisabled: true,\n })\n const result = (await runner.run(this.agent, messages, {\n context,\n })) as RunnerResult\n const endTime = Date.now()\n\n await this.sendLlmRunTracking(result, context, startTime, endTime)\n\n const runResult = this.buildRunResult(result, context, messages.length)\n\n this.logger.logRunResult(runResult, startTime)\n\n return runResult\n } catch (error) {\n const runResult = this.handleInputGuardrailTripwireTriggered(\n error,\n startTime\n )\n if (runResult) {\n return runResult\n }\n\n this.logger.logRunnerError(startTime, error)\n\n throw error\n }\n }\n\n protected getToolsExecuted(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>\n ): ToolExecution[] {\n const toolResultsByCallId = this.getToolResultsByCallId(result.newItems)\n\n return (\n result.newItems\n ?.filter(item => item instanceof RunToolCallItem)\n .map((item: RunToolCallItem) =>\n this.getToolExecutionInfo(\n item as RunToolCallItem,\n context,\n toolResultsByCallId\n )\n )\n .filter(\n (toolExecution: ToolExecution) => toolExecution.toolName !== ''\n ) || []\n )\n }\n\n private getToolResultsByCallId(\n newItems: unknown[] = []\n ): Map<string, string> {\n const map = new Map<string, string>()\n for (const item of newItems) {\n if (!(item instanceof RunToolCallOutputItem)) {\n continue\n }\n const rawItem = item.rawItem as {\n callId?: string\n output?: string | { type?: string; text?: string }\n }\n const callId = rawItem?.callId\n const output = rawItem?.output\n if (callId == null || output == null) {\n continue\n }\n const text = this.extractToolResult(output)\n if (text != null) {\n map.set(callId, text)\n }\n }\n return map\n }\n\n private extractToolResult(\n output: string | { type?: string; text?: string }\n ): string | undefined {\n if (typeof output === 'string') {\n return output\n }\n return output?.type === 'text' && typeof output?.text === 'string'\n ? output.text\n : undefined\n }\n\n private getToolExecutionInfo(\n item: RunToolCallItem,\n context: Context<TPlugins, TExtraData>,\n toolResultsByCallId: Map<string, string>\n ): ToolExecution {\n if (item.rawItem.type !== 'function_call') {\n return {\n toolName: '',\n toolArguments: {},\n }\n }\n const toolName = item.rawItem.name\n const toolArguments = this.getSafeToolArguments(item.rawItem.arguments)\n const toolResults = item.rawItem.callId\n ? toolResultsByCallId.get(item.rawItem.callId)\n : undefined\n\n const toolExecution: ToolExecution = {\n toolName,\n toolArguments,\n toolResults,\n }\n\n if (toolName === RETRIEVE_KNOWLEDGE_TOOL_NAME) {\n return {\n ...toolExecution,\n knowledgebaseSourcesIds: context.knowledgeUsed.sourceIds,\n knowledgebaseChunksIds: context.knowledgeUsed.chunksIds,\n }\n }\n\n return toolExecution\n }\n\n private getSafeToolArguments(\n rawToolArguments: string\n ): Record<string, unknown> {\n try {\n return JSON.parse(rawToolArguments)\n } catch (_error) {\n return {}\n }\n }\n\n protected buildRunResult(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n memoryLength: number\n ): RunResult {\n const outputMessages = result.finalOutput?.messages || []\n const hasExit =\n outputMessages.length === 0 ||\n outputMessages.some(message => message.type === 'exit')\n\n return {\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n messages: hasExit\n ? []\n : (outputMessages.filter(\n message => message.type !== 'exit'\n ) as AgenticOutputMessage[]),\n toolsExecuted: this.getToolsExecuted(result, context),\n exit: hasExit,\n memoryLength,\n error: false,\n inputGuardrailsTriggered: [],\n outputGuardrailsTriggered: [],\n }\n }\n\n private async sendLlmRunTracking(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n startTime: number,\n endTime: number\n ): Promise<void> {\n if (!isProd) {\n return\n }\n if (this.llmConfig.getProviderName() === LLM_PROVIDERS.LITELLM) {\n return\n }\n const rawResponses = result.rawResponses ?? []\n if (rawResponses.length === 0) {\n return\n }\n const botId = context.request.session.bot.id\n const isTest = context.request.session.is_test_integration\n const totalDuration = endTime - startTime\n const durationPerCall = Math.round(totalDuration / rawResponses.length)\n const temperature =\n (this.llmConfig.modelSettings.temperature as number | undefined) ?? 0\n const llmRuns = rawResponses.map(response => ({\n inference_id: this.inferenceId,\n is_test: isTest,\n product_name: TrackProductName.AI_AGENT,\n deployment_name: this.llmConfig.modelName,\n model_name:\n (response.providerData?.model as string | undefined) ??\n this.llmConfig.modelName,\n feature: TrackFeature.AI_AGENT_RUN,\n api_version: this.llmConfig.getApiVersion(),\n num_prompt_tokens: response.usage.inputTokens,\n num_completion_tokens: response.usage.outputTokens,\n duration_in_milliseconds: durationPerCall,\n temperature,\n error: null,\n }))\n\n const client = new HubtypeApiClient(context.authToken)\n await client.trackLlmRuns(botId, {\n llm_runs: llmRuns,\n })\n }\n\n protected handleInputGuardrailTripwireTriggered(\n error: unknown,\n startTime: number\n ): RunResult | undefined {\n if (error instanceof InputGuardrailTripwireTriggered) {\n const runResult: RunResult = {\n startingAgentName: '',\n lastAgentName: '',\n availableSpecialists: [],\n isTransferredToSpecialist: false,\n messages: [],\n memoryLength: 0,\n toolsExecuted: [],\n exit: true,\n error: false,\n inputGuardrailsTriggered: error.result.output.outputInfo,\n outputGuardrailsTriggered: [],\n }\n\n this.logger.logGuardrailTriggered()\n this.logger.logRunResult(runResult, startTime)\n\n return runResult\n }\n }\n}\n"],"names":["InputGuardrailTripwireTriggered","RunContext","Runner","RunToolCallItem","RunToolCallOutputItem","isProd","LLM_PROVIDERS","HubtypeApiClient","TrackFeature","TrackProductName","RETRIEVE_KNOWLEDGE_TOOL_NAME","BaseRunner","messages","context","startTime","Date","runContext","prompt","runner","result","endTime","runResult","error","toolResultsByCallId","item","toolExecution","newItems","map","Map","rawItem","callId","output","text","undefined","toolName","toolArguments","toolResults","rawToolArguments","JSON","_error","memoryLength","outputMessages","hasExit","message","rawResponses","botId","isTest","totalDuration","durationPerCall","Math","temperature","llmRuns","response","client","agent","llmConfig","inferenceId","logger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAWuB;AAC6B;AAGa;AACC;AACX;AAuBhD,MAAeW,UAAUA;IAqB9B,MAAM,IACJC,QAA+B,EAC/BC,OAAsC,EAClB;QACpB,MAAMC,YAAYC,KAAK,GAAG;QAE1B,MAAMC,aAAa,IAAIf,UAAUA,CAACY;QAClC,MAAMI,SAAU,MAAM,IAAI,CAAC,KAAK,CAAC,eAAe,CAACD,eAAgB;QACjE,IAAI,CAAC,MAAM,CAAC,cAAc,CACxB,IAAI,CAAC,SAAS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uBAAuBA,SAAS,KAAK,CAAC,YAAY;gBAClD,0BAA0BJ;gBAC1BE;gBACA,OAAO;YACT;QAEA,MAAMG,SAAS,IAAI9C,gBAAgBA,CAACM,QAAQ,SAAS;QACrD,MAAMwC,OAAO,YAAY,CAACR,OAAO;YAC/B,UAAUM;QACZ;IACF;IAEU,sCACR7B,KAAc,EACdR,SAAiB,EACM;QACvB,IAAIQ,iBAAiBtB,+BAA+BA,EAAE;YACpD,MAAMqB,YAAuB;gBAC3B,mBAAmB;gBACnB,eAAe;gBACf,sBAAsB,EAAE;gBACxB,2BAA2B;gBAC3B,UAAU,EAAE;gBACZ,cAAc;gBACd,eAAe,EAAE;gBACjB,MAAM;gBACN,OAAO;gBACP,0BAA0BC,MAAM,MAAM,CAAC,MAAM,CAAC,UAAU;gBACxD,2BAA2B,EAAE;YAC/B;YAEA,IAAI,CAAC,MAAM,CAAC,qBAAqB;YACjC,IAAI,CAAC,MAAM,CAAC,YAAY,CAACD,WAAWP;YAEpC,OAAOO;QACT;IACF;IAjQA,YACEiC,KAAoC,EACpCC,SAAoB,EACpBC,WAAmB,EACnBC,MAAmB,CACnB;QAVF,uBAAU,SAAV;QACA,uBAAU,aAAV;QACA,uBAAU,eAAV;QACA,uBAAU,UAAV;QAQE,IAAI,CAAC,KAAK,GAAGH;QACb,IAAI,CAAC,SAAS,GAAGC;QACjB,IAAI,CAAC,WAAW,GAAGC;QACnB,IAAI,CAAC,MAAM,GAAGC;IAChB;AAwPF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runners/index.js","sources":["../../../src/runners/index.ts"],"sourcesContent":["export { RouterRunner } from './router-runner'\nexport { SpecialistRunner } from './specialist-runner'\n"],"names":["RouterRunner","SpecialistRunner"],"mappings":";;AAA8C;AACQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runners/router-runner.js","sources":["../../../src/runners/router-runner.ts"],"sourcesContent":["import type { AvailableSpecialist, ResolvedPlugins } from '@botonic/core'\nimport { Handoff } from '@openai/agents'\nimport type { Agent } from '@openai/agents-core'\n\nimport type { Context, RunResult } from '../types'\nimport { BaseRunner, type RunnerResult } from './base-runner'\n\nexport class RouterRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseRunner<TPlugins, TExtraData> {\n protected override buildRunResult(\n result: RunnerResult,\n context: Context<TPlugins, TExtraData>,\n memoryLength: number\n ): RunResult {\n const base = super.buildRunResult(result, context, memoryLength)\n\n const availableSpecialists = this.getAvailableSpecialists()\n const startingAgentName = this.agent.name ?? ''\n const lastAgentName = result.lastAgent?.name ?? ''\n\n return {\n ...base,\n startingAgentName,\n lastAgentName,\n availableSpecialists,\n isTransferredToSpecialist: startingAgentName !== lastAgentName,\n }\n }\n\n protected override handleInputGuardrailTripwireTriggered(\n error: unknown,\n startTime: number\n ): RunResult | undefined {\n const runResult = super.handleInputGuardrailTripwireTriggered(\n error,\n startTime\n )\n if (runResult) {\n // Override attributes to match router agent\n runResult.startingAgentName = this.agent.name\n runResult.lastAgentName = this.agent.name\n runResult.availableSpecialists = this.getAvailableSpecialists()\n runResult.isTransferredToSpecialist = false\n\n return runResult\n }\n return undefined\n }\n\n private getAvailableSpecialists(): AvailableSpecialist[] {\n return (this.agent.handoffs ?? []).map(\n (entry: Agent<any, any> | Handoff<any, any>) => {\n const isHandoff = entry instanceof Handoff\n const agent = isHandoff ? entry.agent : (entry as Agent<any, any>)\n const description = isHandoff\n ? entry.toolDescription\n : agent.handoffDescription\n return { name: agent.name, description }\n }\n )\n }\n}\n"],"names":["Handoff","BaseRunner","RouterRunner","result","context","memoryLength","base","availableSpecialists","startingAgentName","lastAgentName","error","startTime","runResult","undefined","entry","isHandoff","agent","description"],"mappings":";;;;;AACwC;AAIqB;AAEtD,MAAME,YAAYA,SAGfD,UAAUA;IACC,eACjBE,MAAoB,EACpBC,OAAsC,EACtCC,YAAoB,EACT;QACX,MAAMC,OAAO,KAAK,CAAC,eAAeH,QAAQC,SAASC;QAEnD,MAAME,uBAAuB,IAAI,CAAC,uBAAuB;QACzD,MAAMC,oBAAoB,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI;QAC7C,MAAMC,gBAAgBN,OAAO,SAAS,EAAE,QAAQ;QAEhD,OAAO;YACL,GAAGG,IAAI;YACPE;YACAC;YACAF;YACA,2BAA2BC,sBAAsBC;QACnD;IACF;IAEmB,sCACjBC,KAAc,EACdC,SAAiB,EACM;QACvB,MAAMC,YAAY,KAAK,CAAC,sCACtBF,OACAC;QAEF,IAAIC,WAAW;YACb,4CAA4C;YAC5CA,UAAU,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI;YAC7CA,UAAU,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI;YACzCA,UAAU,oBAAoB,GAAG,IAAI,CAAC,uBAAuB;YAC7DA,UAAU,yBAAyB,GAAG;YAEtC,OAAOA;QACT;QACA,OAAOC;IACT;IAEQ,0BAAiD;QACvD,OAAQ,KAAI,CAAC,KAAK,CAAC,QAAQ,IAAI,EAAC,EAAG,GAAG,CACpC,CAACC;YACC,MAAMC,YAAYD,iBAAiBd,OAAOA;YAC1C,MAAMgB,QAAQD,YAAYD,MAAM,KAAK,GAAIA;YACzC,MAAMG,cAAcF,YAChBD,MAAM,eAAe,GACrBE,MAAM,kBAAkB;YAC5B,OAAO;gBAAE,MAAMA,MAAM,IAAI;gBAAEC;YAAY;QACzC;IAEJ;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runners/specialist-runner.js","sources":["../../../src/runners/specialist-runner.ts"],"sourcesContent":["import type { ResolvedPlugins } from '@botonic/core'\nimport { BaseRunner } from './base-runner'\n\nexport class SpecialistRunner<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = unknown,\n> extends BaseRunner<TPlugins, TExtraData> {}\n"],"names":["BaseRunner","SpecialistRunner"],"mappings":";;;AAC0C;AAEnC,MAAMC,gBAAgBA,SAGnBD,UAAUA;AAAwB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"services/hubtype-api-client.js","sources":["../../../src/services/hubtype-api-client.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/naming-convention */\nimport type { BotContext, HubtypeAssistantMessage } from '@botonic/core'\nimport axios from 'axios'\n\nimport { HUBTYPE_API_URL } from '../constants'\nimport type { AgenticInputMessage, Chunk, MemoryOptions } from '../types'\nimport type {\n GetMessagesV2Result,\n HubtypeAssistantMessageV2,\n HubtypeMessage,\n HubtypeMessageV2,\n HubtypeToolMessageV2,\n MessageHistoryResponseV2,\n MessageHistoryV2Params,\n TrackLlmRunsData,\n} from './types'\n\nexport class HubtypeApiClient {\n private readonly authToken: string\n\n constructor(authToken: string) {\n this.authToken = authToken\n }\n\n async retrieveSimilarChunks(\n query: string,\n sourceIds: string[]\n ): Promise<Chunk[]> {\n const url = `${HUBTYPE_API_URL}/external/v1/ai/knowledge_base/similar_chunks/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n const params = {\n query,\n source_ids: sourceIds,\n num_chunks: 5,\n }\n const response = await axios.post(url, params, { headers })\n const chunks = response.data.chunks.map((chunk: Chunk) => ({\n id: chunk.id,\n text: chunk.text,\n }))\n return chunks\n }\n\n async getLocalMessages(\n maxMemoryLength: number,\n previousHubtypeMessages: HubtypeAssistantMessage[],\n localStorageKey: string\n ): Promise<AgenticInputMessage[]> {\n const localBotonicState =\n typeof globalThis !== 'undefined' && globalThis.localStorage\n ? globalThis.localStorage.getItem(localStorageKey)\n : null\n const botonicState = JSON.parse(localBotonicState || '{}')\n const messages = botonicState.messages\n const filteredMessages = messages\n .filter(message => message.data.text)\n .map(message => ({\n role: message.sentBy === 'user' ? 'user' : 'assistant',\n content: message.data.text,\n }))\n .map(message => this.formatMessage(message))\n const resultMessages = [...filteredMessages, ...previousHubtypeMessages]\n\n return resultMessages.slice(-maxMemoryLength)\n }\n\n async getMessagesV2(\n botContext: BotContext,\n options: MemoryOptions,\n previousHubtypeMessages: HubtypeAssistantMessage[]\n ): Promise<GetMessagesV2Result> {\n const url = `${HUBTYPE_API_URL}/external/v2/ai/agent/message_history/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n const params: MessageHistoryV2Params = {\n last_message_id: botContext.input.message_id,\n max_messages: options.maxMessages,\n include_tool_calls: options.includeToolCalls,\n max_full_tool_results: options.maxFullToolResults,\n debug_mode: options.debugMode,\n }\n\n try {\n const response = await axios.get<MessageHistoryResponseV2>(url, {\n headers,\n params,\n })\n const { messages, conversation_id, truncated } = response.data\n const formattedMessages = [...messages, ...previousHubtypeMessages]\n .map(message => this.formatMessageV2(message))\n .filter((message): message is AgenticInputMessage => message !== null)\n\n return {\n messages: formattedMessages,\n conversationId: conversation_id,\n truncated,\n }\n } catch (error) {\n console.error(error)\n throw new Error('Failed to get messages from Hubtype V2 API')\n }\n }\n\n private formatMessageV2(\n message: HubtypeMessageV2\n ): AgenticInputMessage | null {\n switch (message.role) {\n case 'user':\n return {\n role: 'user',\n content: message.content ?? '',\n }\n case 'assistant': {\n const assistantMessage = message as HubtypeAssistantMessageV2\n // If assistant message has tool_calls, include them for context\n // Using double assertion as the OpenAI API supports this format,\n // but the agents SDK types are more restrictive\n if (\n assistantMessage.tool_calls &&\n assistantMessage.tool_calls.length > 0\n ) {\n return {\n role: 'assistant',\n content: assistantMessage.content ?? '',\n tool_calls: assistantMessage.tool_calls.map(tc => ({\n id: tc.id,\n type: tc.type,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n } as unknown as AgenticInputMessage\n }\n // Regular assistant message without tool_calls\n return {\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: assistantMessage.content ?? '',\n },\n ],\n status: 'completed',\n }\n }\n case 'tool': {\n // Tool messages provide context about previous tool executions\n // Using double assertion as the OpenAI API supports this format,\n // but the agents SDK types are more restrictive\n const toolMessage = message as HubtypeToolMessageV2\n return {\n role: 'tool',\n tool_call_id: toolMessage.tool_call_id,\n content: toolMessage.content ?? '',\n } as unknown as AgenticInputMessage\n }\n case 'system':\n return {\n role: 'system',\n content: message.content ?? '',\n }\n default:\n throw new Error(\n `Invalid message role: ${(message as HubtypeMessageV2).role}`\n )\n }\n }\n\n async trackLlmRuns(botId: string, data: TrackLlmRunsData): Promise<void> {\n // Not stop the bot execution if the tracking fails, just log the error\n try {\n const url = `${HUBTYPE_API_URL}/external/v2/conversational_apps/${botId}/track_llm_runs/`\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.authToken}`,\n }\n await axios.post(url, data, { headers })\n } catch (error) {\n console.error('Failed to track LLM runs:', error)\n }\n }\n\n private formatMessage(message: HubtypeMessage): AgenticInputMessage {\n if (message.role === 'user') {\n return {\n content: message.content,\n role: 'user',\n }\n } else if (message.role === 'assistant') {\n return {\n role: 'assistant',\n content: [\n {\n type: 'output_text',\n text: message.content,\n },\n ],\n status: 'completed',\n }\n } else {\n throw new Error('Invalid message role')\n }\n }\n}\n"],"names":["axios","HUBTYPE_API_URL","HubtypeApiClient","query","sourceIds","url","headers","params","response","chunks","chunk","maxMemoryLength","previousHubtypeMessages","localStorageKey","localBotonicState","globalThis","botonicState","JSON","messages","filteredMessages","message","resultMessages","botContext","options","conversation_id","truncated","formattedMessages","error","console","Error","assistantMessage","tc","toolMessage","botId","data","authToken"],"mappings":";;;;;AAAA,uDAAuD;;;;;;;;;;;AAE9B;AAEqB;AAavC,MAAME,gBAAgBA;IAO3B,MAAM,sBACJC,KAAa,EACbC,SAAmB,EACD;QAClB,MAAMC,MAAM,GAAGJ,eAAeA,CAAC,8CAA8C,CAAC;QAC9E,MAAMK,UAAU;YACd,gBAAgB;YAChB,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE;QAC3C;QACA,MAAMC,SAAS;YACbJ;YACA,YAAYC;YACZ,YAAY;QACd;QACA,MAAMI,WAAW,MAAMR,UAAU,CAACK,KAAKE,QAAQ;YAAED;QAAQ;QACzD,MAAMG,SAAS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AAK;gBACH,OAAO;oBACL,MAAM;oBACN,SAASZ,QAAQ,OAAO,IAAI;gBAC9B;YACF;gBACE,MAAM,IAAIS,MACR,CAAC,sBAAsB,EAAGT,QAA6B,IAAI,EAAE;QAEnE;IACF;IAEA,MAAM,aAAaa,KAAa,EAAEC,IAAsB,EAAiB;QACvE,uEAAuE;QACvE,IAAI;YACF,MAAM7B,MAAM,GAAGJ,eAAeA,CAAC,iCAAiC,EAAEgC,MAAM,gBAAgB,CAAC;YACzF,MAAM3B,UAAU;gBACd,gBAAgB;gBAChB,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE;YAC3C;YACA,MAAMN,UAAU,CAACK,KAAK6B,MAAM;gBAAE5B;YAAQ;QACxC,EAAE,OAAOqB,OAAO;YACdC,QAAQ,KAAK,CAAC,6BAA6BD;QAC7C;IACF;IAEQ,cAAcP,OAAuB,EAAuB;QAClE,IAAIA,QAAQ,IAAI,KAAK,QAAQ;YAC3B,OAAO;gBACL,SAASA,QAAQ,OAAO;gBACxB,MAAM;YACR;QACF,OAAO,IAAIA,QAAQ,IAAI,KAAK,aAAa;YACvC,OAAO;gBACL,MAAM;gBACN,SAAS;oBACP;wBACE,MAAM;wBACN,MAAMA,QAAQ,OAAO;oBACvB;iBACD;gBACD,QAAQ;YACV;QACF,OAAO;YACL,MAAM,IAAIS,MAAM;QAClB;IACF;IA5LA,YAAYM,SAAiB,CAAE;QAF/B,uBAAiB,aAAjB;QAGE,IAAI,CAAC,SAAS,GAAGA;IACnB;AA2LF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"services/types.js","sources":["../../../src/services/types.ts"],"sourcesContent":["import type { HubtypeAssistantMessage, HubtypeUserMessage } from '@botonic/core'\nimport type { AgenticInputMessage } from '../types'\n\nexport enum TrackProductName {\n AI_AGENT = 'ai_agent',\n}\n\nexport enum TrackFeature {\n AI_AGENT_RUN = 'ai_agent_run',\n AI_AGENT_GUARDRAIL = 'ai_agent_guardrail',\n}\n\nexport interface LlmRunData {\n inference_id: string\n is_test: boolean\n product_name: string\n deployment_name: string\n model_name: string\n feature: string\n api_version?: string\n num_prompt_tokens: number\n num_completion_tokens: number\n duration_in_milliseconds: number\n temperature: number\n error: string | null\n}\n\nexport interface TrackLlmRunsData {\n llm_runs: LlmRunData[]\n}\n\nexport type HubtypeMessage = HubtypeAssistantMessage | HubtypeUserMessage\n\n// V2 API Types\ninterface HubtypeToolCall {\n id: string\n type: 'function'\n function: {\n name: string\n arguments: string\n }\n}\n\ninterface HubtypeUserMessageV2 {\n role: 'user'\n content: string | null\n}\n\nexport interface HubtypeAssistantMessageV2 {\n role: 'assistant'\n content: string | null\n tool_calls?: HubtypeToolCall[] | null\n}\n\nexport interface HubtypeToolMessageV2 {\n role: 'tool'\n content: string | null\n tool_call_id: string\n}\n\ninterface HubtypeSystemMessageV2 {\n role: 'system'\n content: string | null\n}\n\nexport type HubtypeMessageV2 =\n | HubtypeUserMessageV2\n | HubtypeAssistantMessageV2\n | HubtypeToolMessageV2\n | HubtypeSystemMessageV2\n\nexport interface MessageHistoryResponseV2 {\n messages: HubtypeMessageV2[]\n conversation_id: string | null\n truncated: boolean\n}\n\nexport interface GetMessagesV2Result {\n messages: AgenticInputMessage[]\n conversationId: string | null\n truncated: boolean\n}\n\nexport interface MessageHistoryV2Params {\n last_message_id: string\n max_messages?: number\n include_tool_calls?: boolean\n max_full_tool_results?: number\n debug_mode?: boolean\n}\n"],"names":["TrackProductName","TrackFeature"],"mappings":"AAGO,IAAKA,sBAAgBA,0BAAhBA;;WAAAA;MAEX;AAEM,IAAKC,kBAAYA,0BAAZA;;;WAAAA;MAGX"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/bot-executor.js","sources":["../../../src/structured-output/bot-executor.ts"],"sourcesContent":["import { type BotExecutorMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { BotExecutorMessage }\n\nexport const BotExecutorSchema = z\n .object({\n type: z.literal(OutputMessageType.BotExecutor),\n content: z.object({\n text: z.string(),\n buttons: z.array(\n z.object({\n text: z.string(),\n payload: z.string(),\n })\n ),\n }),\n })\n .describe(\n 'A text message with buttons to allow the bot to execute a specific action. Use it only when asked explicitly in the prompt'\n )\n"],"names":["OutputMessageType","z","BotExecutorSchema"],"mappings":";;;;;AAA0E;AACnD;AAIhB,MAAME,iBAAiBA,GAAGD,QACxB,CAAC;IACN,MAAMA,SAAS,CAACD,6BAA6B;IAC7C,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;QACd,SAASA,OAAO,CACdA,QAAQ,CAAC;YACP,MAAMA,QAAQ;YACd,SAASA,QAAQ;QACnB;IAEJ;AACF,GACC,QAAQ,CACP,8HACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/carousel.js","sources":["../../../src/structured-output/carousel.ts"],"sourcesContent":["import { type CarouselMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { CarouselMessage }\n\nexport const CarouselSchema = z\n .object({\n type: z.literal(OutputMessageType.Carousel),\n content: z.object({\n text: z.string().nullable().optional(),\n elements: z.array(\n z.object({\n title: z.string(),\n subtitle: z.string(),\n image: z.string(),\n button: z.object({\n text: z.string(),\n url: z.string().nullable().optional(),\n }),\n })\n ),\n }),\n })\n .describe('A carousel message containing a list of elements')\n"],"names":["OutputMessageType","z","CarouselSchema"],"mappings":";;;;;AAAuE;AAChD;AAIhB,MAAME,cAAcA,GAAGD,QACrB,CAAC;IACN,MAAMA,SAAS,CAACD,0BAA0B;IAC1C,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;QACpC,UAAUA,OAAO,CACfA,QAAQ,CAAC;YACP,OAAOA,QAAQ;YACf,UAAUA,QAAQ;YAClB,OAAOA,QAAQ;YACf,QAAQA,QAAQ,CAAC;gBACf,MAAMA,QAAQ;gBACd,KAAKA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;YACrC;QACF;IAEJ;AACF,GACC,QAAQ,CAAC,oDAAmD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/exit.js","sources":["../../../src/structured-output/exit.ts"],"sourcesContent":["import { type ExitMessage, OutputMessageType } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { ExitMessage }\n\nexport const ExitSchema = z\n .object({\n type: z.literal(OutputMessageType.Exit),\n })\n .describe(\n 'An exit message. This message should only be used to exit the agent due to out of context or the user asking to exit the conversation'\n )\n"],"names":["OutputMessageType","z","ExitSchema"],"mappings":";;;;;AAAmE;AAC5C;AAIhB,MAAME,UAAUA,GAAGD,QACjB,CAAC;IACN,MAAMA,SAAS,CAACD,sBAAsB;AACxC,GACC,QAAQ,CACP,yIACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/index.js","sources":["../../../src/structured-output/index.ts"],"sourcesContent":["import type { OutputMessage } from '@botonic/core'\nimport { z } from 'zod'\nimport { BotExecutorSchema } from './bot-executor'\nimport { CarouselSchema } from './carousel'\nimport { ExitSchema } from './exit'\nimport { TextSchema } from './text'\nimport { TextWithButtonsSchema } from './text-with-buttons'\n\nexport interface Output {\n messages: OutputMessage[]\n}\n\nconst baseMessageSchemas = [\n TextSchema,\n TextWithButtonsSchema,\n CarouselSchema,\n ExitSchema,\n BotExecutorSchema,\n] as const\nexport const OutputSchema = z\n .object({\n messages: z.array(z.union(baseMessageSchemas)),\n })\n .describe('The messages to be sent to the user')\n\nexport function getOutputSchema(\n externalOutputMessagesSchemas: z.ZodObject<any>[]\n) {\n return z.object({\n messages: z.array(\n z.union([...baseMessageSchemas, ...externalOutputMessagesSchemas])\n ),\n })\n}\n\nexport function getOutputInstructions(): string {\n const example = {\n messages: [\n {\n type: 'text',\n content: {\n text: 'Hello, how can I help you today?',\n },\n },\n ],\n }\n const output = `Return a JSON that follows the output schema provided. Never return multiple output schemas concatenated by a line break.\\n<example>\\n${JSON.stringify(example)}\\n</example>`\n return `<output>\\n${output}\\n</output>`\n}\n"],"names":["z","BotExecutorSchema","CarouselSchema","ExitSchema","TextSchema","TextWithButtonsSchema","baseMessageSchemas","OutputSchema","getOutputSchema","externalOutputMessagesSchemas","getOutputInstructions","example","output","JSON"],"mappings":";;;;;;;;;;;;;AACuB;AAC2B;AACP;AACR;AACA;AACwB;AAM3D,MAAMM,kBAAkBA,GAAG;IACzBF,UAAUA;IACVC,qBAAqBA;IACrBH,cAAcA;IACdC,UAAUA;IACVF,iBAAiBA;CAClB;AACM,MAAMM,YAAYA,GAAGP,QACnB,CAAC;IACN,UAAUA,OAAO,CAACA,OAAO,CAACM,kBAAkBA;AAC9C,GACC,QAAQ,CAAC,uCAAsC;AAE3C,SAASE,eAAeA,CAC7BC,6BAAiD;IAEjD,OAAOT,QAAQ,CAAC;QACd,UAAUA,OAAO,CACfA,OAAO,CAAC;eAAIM,kBAAkBA;eAAKG;SAA8B;IAErE;AACF;AAEO,SAASC,qBAAqBA;IACnC,MAAMC,UAAU;QACd,UAAU;YACR;gBACE,MAAM;gBACN,SAAS;oBACP,MAAM;gBACR;YACF;SACD;IACH;IACA,MAAMC,SAAS,CAAC,sIAAsI,EAAEC,KAAK,SAAS,CAACF,SAAS,YAAY,CAAC;IAC7L,OAAO,CAAC,UAAU,EAAEC,OAAO,WAAW,CAAC;AACzC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/text-with-buttons.js","sources":["../../../src/structured-output/text-with-buttons.ts"],"sourcesContent":["import { OutputMessageType, type TextWithButtonsMessage } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { TextWithButtonsMessage }\n\nexport const TextWithButtonsSchema = z\n .object({\n type: z.literal(OutputMessageType.TextWithButtons),\n content: z.object({\n text: z.string(),\n buttons: z.array(\n z.object({\n text: z.string(),\n url: z.string().nullable().optional(),\n target: z\n .enum(['_blank', '_self'])\n .default('_blank')\n .nullable()\n .optional()\n .describe(\n 'The target of the button when it has an url. If not provided, it will default to _blank.'\n ),\n })\n ),\n }),\n })\n .describe(\n 'A text message with buttons to allow the user to use quick replies'\n )\n"],"names":["OutputMessageType","z","TextWithButtonsSchema"],"mappings":";;;;;AAA8E;AACvD;AAIhB,MAAME,qBAAqBA,GAAGD,QAC5B,CAAC;IACN,MAAMA,SAAS,CAACD,iCAAiC;IACjD,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;QACd,SAASA,OAAO,CACdA,QAAQ,CAAC;YACP,MAAMA,QAAQ;YACd,KAAKA,QAAQ,GAAG,QAAQ,GAAG,QAAQ;YACnC,QAAQA,SACD,CAAC;gBAAC;gBAAU;aAAQ,EACxB,OAAO,CAAC,UACR,QAAQ,GACR,QAAQ,GACR,QAAQ,CACP;QAEN;IAEJ;AACF,GACC,QAAQ,CACP,sEACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"structured-output/text.js","sources":["../../../src/structured-output/text.ts"],"sourcesContent":["import { OutputMessageType, type TextMessage } from '@botonic/core'\nimport { z } from 'zod'\n\nexport type { TextMessage }\n\nexport const TextSchema = z\n .object({\n type: z.literal(OutputMessageType.Text),\n content: z.object({\n text: z.string(),\n }),\n })\n .describe('A text message')\n"],"names":["OutputMessageType","z","TextSchema"],"mappings":";;;;;AAAmE;AAC5C;AAIhB,MAAME,UAAUA,GAAGD,QACjB,CAAC;IACN,MAAMA,SAAS,CAACD,sBAAsB;IACtC,SAASC,QAAQ,CAAC;QAChB,MAAMA,QAAQ;IAChB;AACF,GACC,QAAQ,CAAC,kBAAiB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools/index.js","sources":["../../../src/tools/index.ts"],"sourcesContent":["import type { Tool } from '../types'\n\nexport {\n createRetrieveKnowledge,\n RETRIEVE_KNOWLEDGE_TOOL_NAME,\n} from './retrieve-knowledge'\n\nexport const mandatoryTools: Tool[] = []\n"],"names":["createRetrieveKnowledge","RETRIEVE_KNOWLEDGE_TOOL_NAME","mandatoryTools"],"mappings":";AAK6B;AAEtB,MAAME,cAAcA,GAAW,EAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools/retrieve-knowledge.js","sources":["../../../src/tools/retrieve-knowledge.ts"],"sourcesContent":["import { type RunContext, tool } from '@openai/agents'\nimport { z } from 'zod'\n\nimport { HubtypeApiClient } from '../services/hubtype-api-client'\nimport type { Context } from '../types'\n\nexport const RETRIEVE_KNOWLEDGE_TOOL_NAME = 'retrieve_knowledge'\n\nexport const createRetrieveKnowledge = (sourceIds: string[]) =>\n tool({\n name: RETRIEVE_KNOWLEDGE_TOOL_NAME,\n description:\n 'Consult the knowledge base for information before answering. Use this tool to make sure the information you provide is faithful.',\n parameters: z.object({\n query: z.string().describe('The query to search the knowledge base for'),\n }),\n execute: async (\n input: { query: string },\n runContext?: RunContext<Context>\n ): Promise<string[]> => {\n const context = runContext?.context\n const query = input.query\n if (!context) {\n throw new Error('Context is required')\n }\n const client = new HubtypeApiClient(context.authToken)\n const chunks = await client.retrieveSimilarChunks(query, sourceIds)\n const chunksIds = chunks.map(chunk => chunk.id)\n const chunkTexts = chunks.map(chunk => chunk.text)\n\n context.knowledgeUsed = {\n query,\n sourceIds,\n chunksIds,\n chunkTexts,\n }\n\n return chunkTexts\n },\n })\n"],"names":["tool","z","HubtypeApiClient","RETRIEVE_KNOWLEDGE_TOOL_NAME","createRetrieveKnowledge","sourceIds","input","runContext","context","query","Error","client","chunks","chunksIds","chunk","chunkTexts"],"mappings":";;;;;;;AAAsD;AAC/B;AAE0C;AAG1D,MAAMG,4BAA4BA,GAAG,qBAAoB;AAEzD,MAAMC,uBAAuBA,GAAG,CAACC,YACtCL,IAAIA,CAAC;QACH,MAAMG,4BAA4BA;QAClC,aACE;QACF,YAAYF,QAAQ,CAAC;YACnB,OAAOA,QAAQ,GAAG,QAAQ,CAAC;QAC7B;QACA,SAAS,OACPK,OACAC;YAEA,MAAMC,UAAUD,YAAY;YAC5B,MAAME,QAAQH,MAAM,KAAK;YACzB,IAAI,CAACE,SAAS;gBACZ,MAAM,IAAIE,MAAM;YAClB;YACA,MAAMC,SAAS,IAAIT,gBAAgBA,CAACM,QAAQ,SAAS;YACrD,MAAMI,SAAS,MAAMD,OAAO,qBAAqB,CAACF,OAAOJ;YACzD,MAAMQ,YAAYD,OAAO,GAAG,CAACE,CAAAA,QAASA,MAAM,EAAE;YAC9C,MAAMC,aAAaH,OAAO,GAAG,CAACE,CAAAA,QAASA,MAAM,IAAI;YAEjDN,QAAQ,aAAa,GAAG;gBACtBC;gBACAJ;gBACAQ;gBACAE;YACF;YAEA,OAAOA;QACT;IACF,GAAE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sources":["../../src/types.ts"],"sourcesContent":["import type {\n AgenticOutputMessage,\n AiAgentArgs,\n BotContext,\n GuardrailRule,\n InferenceResponse,\n ResolvedPlugins,\n RunResult,\n} from '@botonic/core'\nimport type {\n Agent,\n AgentInputItem,\n AgentOutputType,\n RunContext as OpenAIRunContext,\n Tool as OpenAITool,\n} from '@openai/agents'\nimport type { ZodType } from 'zod'\n\nimport type { OutputSchema } from './structured-output'\n\nexport interface Context<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n authToken: string\n knowledgeUsed: {\n query: string\n sourceIds: string[]\n chunksIds: string[]\n chunkTexts: string[]\n }\n request: BotContext<TPlugins, TExtraData>\n}\n\nexport type RunContext<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = OpenAIRunContext<Context<TPlugins, TExtraData>>\n\nexport interface CustomTool<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n name: string\n description: string\n schema: ZodType\n func: (\n input?: any,\n runContext?: RunContext<TPlugins, TExtraData>\n ) => Promise<any>\n}\n\nexport interface Chunk {\n id: string\n text: string\n}\n\nexport type Tool<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = OpenAITool<Context<TPlugins, TExtraData>>\n\nexport type AIAgent<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> = Agent<Context<TPlugins, TExtraData>, AgentOutputType<typeof OutputSchema>>\n\nexport interface MemoryOptions {\n maxMessages: number\n includeToolCalls: boolean\n maxFullToolResults: number\n debugMode: boolean\n}\n\nexport interface PluginAiAgentOptions<\n TPlugins extends ResolvedPlugins = ResolvedPlugins,\n TExtraData = any,\n> {\n authToken?: string\n customTools?: CustomTool<TPlugins, TExtraData>[]\n maxRetries?: number\n timeout?: number\n memory?: Partial<MemoryOptions>\n /** Enable debug logging for AI agent configuration and execution details. */\n enableDebug?: boolean\n /** Key for the local storage to to get messages in local development mode */\n localStorageKey?: string\n}\n\nexport interface ResultRawResponse {\n usage: {\n inputTokens: number\n outputTokens: number\n }\n providerData?: Record<string, unknown>\n}\n\nexport type AgenticInputMessage = AgentInputItem\n\nexport type {\n AgenticOutputMessage,\n AiAgentArgs,\n GuardrailRule,\n InferenceResponse,\n RunResult,\n}\n"],"names":[],"mappings":"AAyGC"}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes