{"version":3,"sources":["../../../src/agents/requirement/agent.ts"],"names":["RequirementAgent","BaseAgent","emitter","Emitter","root","child","namespace","creator","input","runner","RequirementAgentRunner","memory","UnconstrainedMemory","tools","requirements","saveIntermediateSteps","finalAnswerAsTool","toolCallChecker","middlewares","push","register","_run","options","run","execution","maxRetriesPerStep","totalMaxRetries","maxIterations","createToolCallChecker","llm","expectedOutput","templates","newMessages","processInput","addMessages","messages","finalState","reset","addMany","lastPair","slice","answer","Error","result","state","prompt","userMessage","UserMessage","task","render","context","undefined","config","Object","assign","checker","ToolCallChecker","enabled","meta","name","description","length","extraDescription","map","tool","join","overrides","finalized","mapObj","system","RequirementAgentSystemPrompt","RequirementAgentTaskPrompt","toolError","RequirementAgentToolErrorPrompt","toolNoResult","RequirementAgentToolNoResultPrompt","key","defaultTemplate","override","PromptTemplate","role","instructions","notes","update","defaults","pickBy","isEmptyish","castArray","v","isDefined","createSnapshot","shallowCopy"],"mappings":";;;;;;;;;;;;;;;;;AAqFO,MAAMA,yBAAyBC,kBAAAA,CAAAA;EArFtC;;;EA0FkBC,OAAAA,GAAUC,mBAAAA,CAAQC,KAAKC,KAAAA,CAAiC;IACtEC,SAAAA,EAAW;AAAC,MAAA,OAAA;AAAS,MAAA;;IACrBC,OAAAA,EAAS;GACX,CAAA;AAEmBC,EAAAA,KAAAA;EAETC,MAAAA,GAEoBC,iCAAAA;AAE9B,EAAA,WAAA,CAAYF,KAAAA,EAA8B;AACxC,IAAA,KAAA,EAAK;AACL,IAAA,IAAA,CAAKA,KAAAA,GAAQ;MACX,GAAGA,KAAAA;MACHG,MAAAA,EAAQH,KAAAA,CAAMG,MAAAA,IAAU,IAAIC,2CAAAA,EAAAA;MAC5BC,KAAAA,EAAOL,KAAAA,CAAMK,SAAS,EAAA;MACtBC,YAAAA,EAAcN,KAAAA,CAAMM,gBAAgB,EAAA;AACpCC,MAAAA,qBAAAA,EAAuBP,MAAMO,qBAAAA,IAAyB,IAAA;AACtDC,MAAAA,iBAAAA,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K,CAAA,CACvBnB,GAAAA,CAAI,CAACyB,CAAAA,KAAM,CAAA,EAAA,EAAKA,CAAAA,CAAAA,CAAG,CAAA,CACnBvB,KAAK,IAAA;AACd,SAAA,EACAwB,gBAAAA;OAEJ,CAAA;AACF,IAAA;AAEA,IAAA,OAAOtB,SAAAA;AACT,EAAA;EAEAuB,cAAAA,GAAiB;AACf,IAAA,OAAO;AACL,MAAA,GAAG,MAAMA,cAAAA,EAAAA;MACTlF,KAAAA,EAAOmF,qBAAAA,CAAY,KAAKnF,KAAK,CAAA;AAC7BN,MAAAA,OAAAA,EAAS,IAAA,CAAKA,OAAAA;AACdO,MAAAA,MAAAA,EAAQ,IAAA,CAAKA;AACf,KAAA;AACF,EAAA;AAEA,EAAA,IAAIE,OAAOA,MAAAA,EAAoB;AAC7B,IAAA,IAAA,CAAKH,MAAMG,MAAAA,GAASA,MAAAA;AACtB,EAAA;AAEA,EAAA,IAAIA,MAAAA,GAAqB;AACvB,IAAA,OAAO,KAAKH,KAAAA,CAAMG,MAAAA;AACpB,EAAA;AACF","file":"agent.cjs","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BaseAgent } from \"@/agents/base.js\";\nimport { AnyTool } from \"@/tools/base.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { AgentMeta } from \"@/agents/types.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\nimport type { GetRunContext, MiddlewareType } from \"@/context.js\";\nimport { UnconstrainedMemory } from \"@/memory/unconstrainedMemory.js\";\nimport { Message, UserMessage } from \"@/backend/message.js\";\nimport { shallowCopy } from \"@/serializer/utils.js\";\nimport { mapObj } from \"@/internals/helpers/object.js\";\nimport { PromptTemplate } from \"@/template.js\";\nimport {\n  RequirementAgentCallbacks,\n  RequirementAgentExecutionConfig,\n  RequirementAgentOutput,\n  RequirementAgentRunInput,\n  RequirementAgentRunOptions,\n  RequirementAgentTemplates,\n} from \"./types.js\";\nimport {\n  RequirementAgentSystemPrompt,\n  RequirementAgentTaskPrompt,\n  RequirementAgentToolErrorPrompt,\n  RequirementAgentToolNoResultPrompt,\n} from \"./prompts.js\";\nimport { Requirement } from \"./requirements/requirement.js\";\nimport { RequirementAgentRunner } from \"./runner.js\";\nimport { ToolCallChecker, ToolCallCheckerConfig } from \"./utils/toolCallChecker.js\";\nimport { isDefined, isEmptyish, pickBy } from \"remeda\";\nimport { castArray } from \"@/internals/helpers/array.js\";\nimport type { RequiredExcept } from \"@/internals/types.js\";\n\nexport type RequirementAgentTemplateFactory<K extends keyof RequirementAgentTemplates> = (\n  template: RequirementAgentTemplates[K],\n) => RequirementAgentTemplates[K];\n\nexport interface RequirementAgentInput {\n  llm: ChatModel;\n  memory?: BaseMemory;\n  tools?: AnyTool[];\n  requirements?: Requirement[];\n  name?: string;\n  description?: string;\n  role?: string;\n  instructions?: string | string[];\n  notes?: string | string[];\n  toolCallChecker?: boolean | ToolCallCheckerConfig;\n  finalAnswerAsTool?: boolean;\n  saveIntermediateSteps?: boolean;\n  execution?: RequirementAgentExecutionConfig;\n  templates?: Partial<{\n    [K in keyof RequirementAgentTemplates]:\n      | RequirementAgentTemplates[K]\n      | RequirementAgentTemplateFactory<K>;\n  }>;\n  middlewares?: MiddlewareType<RequirementAgent>[];\n}\n\ntype InternalRequirementAgentInput = RequiredExcept<\n  RequirementAgentInput,\n  | \"role\"\n  | \"instructions\"\n  | \"name\"\n  | \"description\"\n  | \"templates\"\n  | \"notes\"\n  | \"execution\"\n  | \"middlewares\"\n>;\n\n/**\n * RequirementAgent - A declarative AI agent with rule-based constraints\n *\n * The RequirementAgent provides predictable, controlled execution behavior across\n * different language models through rule-based constraints (Requirements).\n * Requirements can be configured as strict or flexible as necessary, adapting to\n * task requirements while ensuring consistent execution regardless of the underlying\n * model's reasoning or tool-calling capabilities.\n */\nexport class RequirementAgent extends BaseAgent<\n  RequirementAgentRunInput,\n  RequirementAgentOutput,\n  RequirementAgentRunOptions\n> {\n  public readonly emitter = Emitter.root.child<RequirementAgentCallbacks>({\n    namespace: [\"agent\", \"requirement\"],\n    creator: this,\n  });\n\n  protected readonly input: InternalRequirementAgentInput;\n\n  protected runner: new (\n    ...args: ConstructorParameters<typeof RequirementAgentRunner>\n  ) => RequirementAgentRunner = RequirementAgentRunner;\n\n  constructor(input: RequirementAgentInput) {\n    super();\n    this.input = {\n      ...input,\n      memory: input.memory || new UnconstrainedMemory(),\n      tools: input.tools || [],\n      requirements: input.requirements || [],\n      saveIntermediateSteps: input.saveIntermediateSteps ?? true,\n      finalAnswerAsTool: input.finalAnswerAsTool ?? true,\n      toolCallChecker: input.toolCallChecker ?? true,\n    };\n    if (input.middlewares) {\n      this.middlewares.push(...input.middlewares);\n    }\n  }\n\n  static {\n    this.register();\n  }\n\n  protected async _run(\n    input: RequirementAgentRunInput,\n    options: RequirementAgentRunOptions = {},\n    run: GetRunContext<typeof this>,\n  ): Promise<RequirementAgentOutput> {\n    const execution: RequirementAgentExecutionConfig = {\n      maxRetriesPerStep: 3,\n      totalMaxRetries: 20,\n      maxIterations: 20,\n      ...this.input.execution,\n      ...options.execution,\n    };\n\n    const toolCallChecker = this.createToolCallChecker();\n\n    const runner = new this.runner(\n      this.input.llm,\n      execution,\n      this.input.tools || [],\n      this.input.requirements || [],\n      input.expectedOutput || null,\n      toolCallChecker,\n      run,\n      this.input.finalAnswerAsTool,\n      this.templates,\n    );\n\n    // Process input messages\n    const newMessages = this.processInput(input);\n    await runner.addMessages([...this.memory.messages]);\n    await runner.addMessages(newMessages);\n\n    // Run the agent\n    const finalState = await runner.run();\n\n    // Update memory\n    if (this.input.saveIntermediateSteps) {\n      this.memory.reset();\n      await this.memory.addMany(finalState.memory.messages);\n    } else {\n      await this.memory.addMany(newMessages);\n      // Add last tool call pair\n      const messages = finalState.memory.messages;\n      const lastPair = messages.slice(-2);\n      await this.memory.addMany(lastPair);\n    }\n\n    if (!finalState.answer) {\n      throw new Error(\"Agent did not produce a final answer\");\n    }\n\n    return {\n      result: finalState.answer,\n      memory: finalState.memory,\n      state: finalState,\n    };\n  }\n\n  protected processInput(input: RequirementAgentRunInput): Message[] {\n    if (!input.prompt) {\n      return [];\n    }\n\n    const userMessage = new UserMessage(\n      this.templates.task.render({\n        prompt: input.prompt,\n        context: input.context,\n        expectedOutput: typeof input.expectedOutput === \"string\" ? input.expectedOutput : undefined,\n      }),\n    );\n\n    return [userMessage];\n  }\n\n  protected createToolCallChecker(): ToolCallChecker {\n    const config: ToolCallCheckerConfig = {};\n\n    if (typeof this.input.toolCallChecker === \"object\") {\n      Object.assign(config, this.input.toolCallChecker);\n    }\n\n    const checker = new ToolCallChecker(config);\n    checker.enabled = this.input.toolCallChecker !== false;\n    return checker;\n  }\n\n  get meta(): AgentMeta {\n    const tools = this.input.tools || [];\n\n    return {\n      name: this.input.name ?? \"Requirement\",\n      tools,\n      description:\n        this.input.description ??\n        \"The RequirementAgent is a declarative AI agent implementation that provides predictable, \" +\n          \"controlled execution behavior across different language models through rule-based constraints.\",\n      ...(tools.length > 0 && {\n        extraDescription: [\n          `Tools that I can use to accomplish given task.`,\n          ...tools.map((tool) => `Tool '${tool.name}': ${tool.description}.`),\n        ].join(\"\\n\"),\n      }),\n    };\n  }\n\n  protected get templates(): RequirementAgentTemplates {\n    const overrides = this.input.templates || {};\n    const finalized = mapObj({\n      system: RequirementAgentSystemPrompt,\n      task: RequirementAgentTaskPrompt,\n      toolError: RequirementAgentToolErrorPrompt,\n      toolNoResult: RequirementAgentToolNoResultPrompt,\n    } as RequirementAgentTemplates)((\n      key,\n      defaultTemplate: RequirementAgentTemplates[typeof key],\n    ) => {\n      const override = overrides[key] ?? defaultTemplate;\n      if (override instanceof PromptTemplate) {\n        return override;\n      }\n      return override(defaultTemplate) ?? defaultTemplate;\n    });\n\n    if (this.input.role || this.input.instructions || this.input.notes) {\n      finalized.system.update({\n        defaults: pickBy(\n          {\n            role: this.input.role,\n            instructions: isEmptyish(this.input.instructions)\n              ? undefined\n              : castArray(this.input.instructions)\n                  .map((v) => `- ${v}`)\n                  .join(\"\\n\"),\n            notes: isEmptyish(this.input.notes)\n              ? undefined\n              : castArray(this.input.notes)\n                  .map((v) => `- ${v}`)\n                  .join(\"\\n\"),\n          },\n          isDefined,\n        ),\n      });\n    }\n\n    return finalized;\n  }\n\n  createSnapshot() {\n    return {\n      ...super.createSnapshot(),\n      input: shallowCopy(this.input),\n      emitter: this.emitter,\n      runner: this.runner,\n    };\n  }\n\n  set memory(memory: BaseMemory) {\n    this.input.memory = memory;\n  }\n\n  get memory(): BaseMemory {\n    return this.input.memory!;\n  }\n}\n"]}