@nebulaos/core 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +21 -0
- package/README.md +206 -206
- package/dist/agent/Agent.d.ts +5 -0
- package/dist/agent/Agent.js +18 -0
- package/dist/agent/skills/index.d.ts +8 -0
- package/package.json +15 -14
- package/dist/index.cjs +0 -2958
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -3425
- package/dist/index.js.map +0 -1
- package/dist/tsup.config.d.ts +0 -2
- package/dist/tsup.config.js +0 -11
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../index.ts","../agent/BaseAgent.ts","../tracing/index.ts","../logger/styles.ts","../logger/formatters.ts","../logger/agent-logger.ts","../logger/workflow-logger.ts","../logger/index.ts","../agent/Agent.ts","../agent/memory/in-memory.ts","../agent/tools/index.ts","../workflow/Workflow.ts","../workflow/adapters.ts","../events/schemas.ts","../lgpd/index.ts","../eval/index.ts","../utils/schema-to-zod.ts","../multi-agent/types/index.ts","../multi-agent/utils/memory.ts","../multi-agent/agent-as-tool/AgentAsTool.ts","../multi-agent/utils/prompts.ts","../multi-agent/utils/guardrails.ts","../multi-agent/router-team/RouterTeam.ts","../multi-agent/handoff-team/HandoffTeam.ts","../multi-agent/hierarchical-team/HierarchicalTeam.ts","../multi-agent/pipeline-team/PipelineTeam.ts","../multi-agent/committee-team/CommitteeTeam.ts"],"sourcesContent":["// Agent\r\nexport * from \"./agent/BaseAgent.js\";\r\nexport * from \"./agent/Agent.js\";\r\nexport * from \"./agent/provider/index.js\";\r\nexport * from \"./agent/memory/index.js\";\r\nexport * from \"./agent/tools/index.js\";\r\nexport * from \"./agent/events/events.js\";\r\n\r\n// Logger\r\nexport * from \"./logger/index.js\";\r\n\r\n// Workflow\r\nexport * from \"./workflow/Workflow.js\";\r\nexport * from \"./workflow/adapters.js\";\r\nexport * from \"./workflow/events.js\";\r\n\r\n// Events (Shared Schemas)\r\nexport * from \"./events/schemas.js\";\r\n\r\n// LGPD\r\nexport * from \"./lgpd/index.js\";\r\n\r\n// Eval\r\nexport * from \"./eval/index.js\";\r\n\r\n// Utils\r\nexport * from \"./utils/schema-to-zod.js\";\r\n\r\n// Tracing (Telemetry)\r\nexport * from \"./tracing/index.js\";\r\n\r\n// Re-export zod for convenience\r\nexport { z } from \"zod\";\r\n\r\n// Multi-Agent\r\nexport * from \"./multi-agent/index.js\";\r\n","import { EventEmitter } from \"events\";\r\nimport { AgentResult } from \"./Agent.js\";\r\nimport { Tracing } from \"../tracing/index.js\";\r\nimport type { AgentEventMap, AgentEventName } from \"./events/events.js\";\r\nimport { IPIIMasker } from \"../lgpd/index.js\";\r\nimport type { IMemory } from \"./memory/index.js\";\r\nimport type { Message } from \"./provider/index.js\";\r\nimport type { AgentExecuteOptions } from \"./Agent.js\";\r\n\r\nexport abstract class BaseAgent {\r\n public readonly name: string;\r\n private emitter = new EventEmitter();\r\n protected piiMasker?: IPIIMasker;\r\n protected memory?: IMemory;\r\n\r\n constructor(name: string, piiMasker?: IPIIMasker, memory?: IMemory) {\r\n this.name = name;\r\n this.piiMasker = piiMasker;\r\n this.memory = memory;\r\n }\r\n\r\n /**\r\n * Executes the agent. All agent-like implementations (including multi-agent teams)\r\n * must accept an optional input string and optional execution options.\r\n */\r\n abstract execute(input?: string, options?: AgentExecuteOptions): Promise<AgentResult>;\r\n\r\n /**\r\n * Adds a message to this agent's memory (if configured).\r\n * Multi-agent teams MUST provide a memory implementation if they expect to be used\r\n * through standardized execution surfaces (e.g., HTTP gateways).\r\n */\r\n async addMessage(message: Message): Promise<void> {\r\n if (!this.memory) {\r\n throw new Error(`Agent '${this.name}' does not have memory configured`);\r\n }\r\n await this.memory.addMessage(message);\r\n }\r\n\r\n // ==========================================================================\r\n // Typed Event Emitter Methods\r\n // ==========================================================================\r\n\r\n /**\r\n * Emits a typed event with automatic context injection (trace, timestamp).\r\n * \r\n * @param event The event name (e.g., 'agent:execution:start')\r\n * @param payload The event payload containing 'data' and optional context like 'correlationId'\r\n */\r\n protected emit<K extends AgentEventName>(\r\n event: K,\r\n payload: {\r\n data: AgentEventMap[K][\"data\"];\r\n correlationId?: string;\r\n runId?: string;\r\n }\r\n ): boolean {\r\n const traceContext = Tracing.getContext();\r\n \r\n // Construct the full event object matching the Zod schema\r\n let fullEvent: any = {\r\n type: event,\r\n timestamp: new Date().toISOString(),\r\n trace: {\r\n traceId: traceContext?.traceId || `fallback-${Date.now()}`,\r\n spanId: traceContext?.spanId || `fallback-${Date.now()}`,\r\n parentSpanId: traceContext?.parentId,\r\n },\r\n correlationId: payload.correlationId,\r\n runId: payload.runId,\r\n data: payload.data,\r\n };\r\n\r\n if (this.piiMasker) {\r\n fullEvent = this.maskEventData(fullEvent);\r\n }\r\n\r\n return this.emitter.emit(event, fullEvent);\r\n }\r\n\r\n public on<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this {\r\n this.emitter.on(event, listener as (...args: any[]) => void);\r\n return this;\r\n }\r\n\r\n public once<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this {\r\n this.emitter.once(event, listener as (...args: any[]) => void);\r\n return this;\r\n }\r\n\r\n public off<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this {\r\n this.emitter.off(event, listener as (...args: any[]) => void);\r\n return this;\r\n }\r\n\r\n /**\r\n * Recursively masks PII in the event payload\r\n */\r\n private maskEventData<T>(data: T): T {\r\n if (!this.piiMasker) return data;\r\n\r\n if (typeof data === \"string\") {\r\n return this.piiMasker.mask(data) as T;\r\n }\r\n\r\n if (Array.isArray(data)) {\r\n return data.map(item => this.maskEventData(item)) as T;\r\n }\r\n\r\n if (typeof data === \"object\" && data !== null) {\r\n if (data instanceof Date) return data;\r\n if (data instanceof Error) {\r\n const maskedError: any = {\r\n name: data.name,\r\n message: this.maskEventData(data.message),\r\n stack: data.stack\r\n };\r\n return maskedError as T;\r\n }\r\n\r\n const maskedObj: any = {};\r\n for (const key in data) {\r\n if (Object.prototype.hasOwnProperty.call(data, key)) {\r\n maskedObj[key] = this.maskEventData((data as any)[key]);\r\n }\r\n }\r\n return maskedObj;\r\n }\r\n\r\n return data;\r\n }\r\n}\r\n","import { AsyncLocalStorage } from \"node:async_hooks\";\r\nimport { randomUUID } from \"node:crypto\";\r\nimport type {\r\n ITelemetryExporter,\r\n TelemetryEventV1,\r\n TelemetrySpanKind,\r\n TelemetrySpanStatus,\r\n} from \"@nebulaos/types\";\r\n\r\nexport interface TracingContext {\r\n traceId: string;\r\n spanId: string;\r\n parentId?: string;\r\n}\r\n\r\nexport interface SpanStartInput<K extends TelemetrySpanKind = TelemetrySpanKind> {\r\n kind: K;\r\n name: string;\r\n data?: Record<string, unknown>;\r\n correlationId?: string;\r\n runId?: string;\r\n}\r\n\r\nexport interface SpanEndInput<K extends TelemetrySpanKind = TelemetrySpanKind> {\r\n status: TelemetrySpanStatus;\r\n data?: Record<string, unknown>;\r\n}\r\n\r\nexport class ActiveSpan<K extends TelemetrySpanKind = TelemetrySpanKind> {\r\n private ended = false;\r\n\r\n constructor(\r\n public readonly traceId: string,\r\n public readonly spanId: string,\r\n public readonly parentSpanId: string | undefined,\r\n public readonly kind: K,\r\n public readonly name: string,\r\n private readonly correlationId: string | undefined,\r\n private readonly runId: string | undefined,\r\n private readonly exporter: ITelemetryExporter,\r\n ) {}\r\n\r\n async end(input: SpanEndInput<K>): Promise<void> {\r\n if (this.ended) return;\r\n this.ended = true;\r\n\r\n const event: TelemetryEventV1 = {\r\n v: 1,\r\n type: \"telemetry:span:end\",\r\n timestamp: new Date().toISOString(),\r\n trace: {\r\n traceId: this.traceId,\r\n spanId: this.spanId,\r\n parentSpanId: this.parentSpanId,\r\n },\r\n correlationId: this.correlationId,\r\n runId: this.runId,\r\n status: input.status,\r\n span: {\r\n kind: this.kind,\r\n name: this.name,\r\n // The contract expects a kind-specific shape, but we keep this generic here.\r\n // The callers are responsible for providing kind-specific keys.\r\n data: input.data as any,\r\n } as any,\r\n };\r\n\r\n try {\r\n await this.exporter.exportBatch([event]);\r\n } catch {\r\n // Telemetry must never break execution.\r\n }\r\n }\r\n\r\n get isEnded(): boolean {\r\n return this.ended;\r\n }\r\n}\r\n\r\nconst storage = new AsyncLocalStorage<TracingContext>();\r\n\r\nclass NoopTelemetryExporter implements ITelemetryExporter {\r\n async exportBatch(_events: TelemetryEventV1[]): Promise<void> {\r\n // noop\r\n }\r\n}\r\n\r\nexport class Tracing {\r\n private static exporter: ITelemetryExporter = new NoopTelemetryExporter();\r\n\r\n static setExporter(exporter: ITelemetryExporter): void {\r\n this.exporter = exporter;\r\n }\r\n\r\n /**\r\n * Gets the current trace context.\r\n * Returns undefined if called outside of a traced execution.\r\n */\r\n static getContext(): TracingContext | undefined {\r\n return storage.getStore();\r\n }\r\n\r\n /**\r\n * Gets the current trace context or creates a dummy one if none exists.\r\n * Useful for logging where you always want *some* ID.\r\n */\r\n static getContextOrDummy(): TracingContext {\r\n const context = storage.getStore();\r\n if (context) return context;\r\n\r\n return {\r\n traceId: \"no-trace\",\r\n spanId: \"no-span\",\r\n };\r\n }\r\n\r\n /**\r\n * Runs a function inside a new telemetry span and exports span lifecycle events.\r\n */\r\n static async withSpan<T, K extends TelemetrySpanKind>(\r\n input: SpanStartInput<K>,\r\n fn: (span: ActiveSpan<K>) => Promise<T>\r\n ): Promise<T> {\r\n const parent = storage.getStore();\r\n\r\n const traceId = parent?.traceId ?? randomUUID();\r\n const parentSpanId = parent?.spanId;\r\n const spanId = randomUUID();\r\n\r\n const startedAt = new Date().toISOString();\r\n\r\n const startEvent: TelemetryEventV1 = {\r\n v: 1,\r\n type: \"telemetry:span:start\",\r\n timestamp: startedAt,\r\n trace: {\r\n traceId,\r\n spanId,\r\n parentSpanId,\r\n },\r\n correlationId: input.correlationId,\r\n runId: input.runId,\r\n span: {\r\n kind: input.kind,\r\n name: input.name,\r\n data: (input.data ?? {}) as any,\r\n } as any,\r\n };\r\n\r\n try {\r\n await this.exporter.exportBatch([startEvent]);\r\n } catch {\r\n // Telemetry must never break execution.\r\n }\r\n\r\n const context: TracingContext = {\r\n traceId,\r\n spanId,\r\n parentId: parentSpanId,\r\n };\r\n\r\n const activeSpan = new ActiveSpan(\r\n traceId,\r\n spanId,\r\n parentSpanId,\r\n input.kind,\r\n input.name,\r\n input.correlationId,\r\n input.runId,\r\n this.exporter\r\n );\r\n\r\n return storage.run(context, async () => {\r\n try {\r\n const result = await fn(activeSpan);\r\n if (!activeSpan.isEnded) await activeSpan.end({ status: \"success\" } as any);\r\n return result;\r\n } catch (error) {\r\n await activeSpan.end({ status: \"error\" } as any);\r\n throw error;\r\n }\r\n });\r\n }\r\n}\r\n","/**\r\n * ANSI escape codes for terminal styling\r\n * Separated for maintainability and reusability\r\n */\r\n\r\nexport const COLORS = {\r\n // Foreground colors\r\n black: \"\\x1b[30m\",\r\n red: \"\\x1b[31m\",\r\n green: \"\\x1b[32m\",\r\n yellow: \"\\x1b[33m\",\r\n blue: \"\\x1b[34m\",\r\n magenta: \"\\x1b[35m\",\r\n cyan: \"\\x1b[36m\",\r\n white: \"\\x1b[37m\",\r\n gray: \"\\x1b[90m\",\r\n\r\n // Bright variants\r\n brightRed: \"\\x1b[91m\",\r\n brightGreen: \"\\x1b[92m\",\r\n brightYellow: \"\\x1b[93m\",\r\n brightBlue: \"\\x1b[94m\",\r\n brightMagenta: \"\\x1b[95m\",\r\n brightCyan: \"\\x1b[96m\",\r\n\r\n // Custom colors (256-color mode)\r\n pink: \"\\x1b[38;5;213m\", // Rosa/Pink - estilo NestJS\r\n\r\n // Styles\r\n reset: \"\\x1b[0m\",\r\n bold: \"\\x1b[1m\",\r\n dim: \"\\x1b[2m\",\r\n italic: \"\\x1b[3m\",\r\n underline: \"\\x1b[4m\",\r\n} as const;\r\n\r\n/**\r\n * Predefined color schemes for different log levels\r\n * Using bright variants for better visibility\r\n */\r\nexport const LOG_LEVEL_COLORS = {\r\n debug: COLORS.pink, // Rosa/Pink (NestJS style)\r\n info: COLORS.brightGreen, // Verde (success/positive)\r\n warn: COLORS.brightYellow, // Amarelo (warning)\r\n error: COLORS.brightRed, // Vermelho (error)\r\n} as const;\r\n\r\n/**\r\n * Tree characters for nested log lines\r\n */\r\nexport const TREE_CHARS = {\r\n branch: \"├─\",\r\n last: \"└─\",\r\n vertical: \"│ \",\r\n space: \" \",\r\n} as const;\r\n\r\n","/**\r\n * Logging formatters module\r\n * \r\n * Contains pure functions for formatting log messages.\r\n * Each formatter is composable and testable.\r\n */\r\n\r\nimport { COLORS, LOG_LEVEL_COLORS, TREE_CHARS } from \"./styles.js\";\r\nimport type { LogLevel } from \"./index.js\";\r\nimport type { TraceContext } from \"../events/schemas.js\";\r\n\r\n/**\r\n * Formats a complete log line in the format:\r\n * [Nebula LEVEL | Agent/Workflow name] timestamp [TraceID] message\r\n * \r\n * The entire line is colored according to the log level.\r\n */\r\nexport function formatLogLine(\r\n level: LogLevel,\r\n entityName: string | null,\r\n message: string,\r\n entityType: \"agent\" | \"workflow\" | null = null,\r\n trace?: TraceContext\r\n): string {\r\n const timestamp = new Date().toISOString().replace(\"T\", \" \").split(\".\")[0];\r\n const levelColor = (level === \"none\" ? COLORS.reset : LOG_LEVEL_COLORS[level]) || COLORS.reset;\r\n const levelUpper = level.toUpperCase();\r\n\r\n // Build the prefix based on whether we have an entity or not\r\n let prefix: string;\r\n if (entityName) {\r\n const entityLabel = entityType === \"workflow\" ? \"Workflow\" : \"Agent\";\r\n const entityColor = entityType === \"workflow\" ? COLORS.brightBlue : COLORS.green;\r\n\r\n prefix = (\r\n `${COLORS.bold}[Nebula ${levelUpper} | ` +\r\n `${entityColor}${COLORS.italic}${entityLabel} ${entityName}${COLORS.reset}${levelColor}${COLORS.bold}]${COLORS.reset}`\r\n );\r\n } else {\r\n prefix = (\r\n `${COLORS.bold}[Nebula ${levelUpper}]${COLORS.reset}`\r\n );\r\n }\r\n\r\n // Timestamp between prefix and message\r\n const timestampStr = `${COLORS.dim}${timestamp}${COLORS.reset}`;\r\n\r\n // Apply level color to the entire line\r\n return `${levelColor}${prefix} ${timestampStr} ${message}${COLORS.reset}`;\r\n}\r\n\r\n/**\r\n * Formats metadata as nested tree structure\r\n * \r\n * @param meta - Object with key-value pairs\r\n * @param isLastGroup - If true, uses └─ for last item, otherwise ├─\r\n * @returns Array of formatted lines\r\n */\r\nexport function formatMetadata(\r\n meta: Record<string, any>,\r\n isLastGroup = true\r\n): string[] {\r\n const entries = Object.entries(meta);\r\n if (entries.length === 0) return [];\r\n\r\n return entries.map(([key, value], index) => {\r\n const isLast = index === entries.length - 1;\r\n const char = isLast && isLastGroup ? TREE_CHARS.last : TREE_CHARS.branch;\r\n const formattedValue = formatValue(value);\r\n\r\n return ` ${COLORS.dim}${char}${COLORS.reset} ${COLORS.bold}${key}:${COLORS.reset} ${formattedValue}`;\r\n });\r\n}\r\n\r\n/**\r\n * Formats a single value for display\r\n * Handles different types appropriately\r\n */\r\nfunction formatValue(value: any): string {\r\n if (value === null) return `${COLORS.dim}null${COLORS.reset}`;\r\n if (value === undefined) return `${COLORS.dim}undefined${COLORS.reset}`;\r\n\r\n if (typeof value === \"string\") {\r\n // Highlight important values\r\n if (value.includes(\"✓\") || value.includes(\"Success\")) {\r\n return `${COLORS.green}${value}${COLORS.reset}`;\r\n }\r\n if (value.includes(\"❌\") || value.includes(\"Error\")) {\r\n return `${COLORS.red}${value}${COLORS.reset}`;\r\n }\r\n return value;\r\n }\r\n\r\n if (typeof value === \"number\") {\r\n return `${COLORS.yellow}${value}${COLORS.reset}`;\r\n }\r\n\r\n if (typeof value === \"boolean\") {\r\n return value\r\n ? `${COLORS.green}${value}${COLORS.reset}`\r\n : `${COLORS.red}${value}${COLORS.reset}`;\r\n }\r\n\r\n // Objects and arrays\r\n try {\r\n return `${COLORS.dim}${JSON.stringify(value)}${COLORS.reset}`;\r\n } catch {\r\n return `${COLORS.dim}[Object]${COLORS.reset}`;\r\n }\r\n}\r\n\r\n/**\r\n * Formats an error with stack trace\r\n */\r\nexport function formatError(error: Error | any): string[] {\r\n const lines: string[] = [];\r\n\r\n if (error instanceof Error) {\r\n lines.push(` ${TREE_CHARS.branch} ${COLORS.red}${error.message}${COLORS.reset}`);\r\n\r\n if (error.stack) {\r\n const stackLines = error.stack.split(\"\\n\").slice(1, 4); // First 3 stack frames\r\n stackLines.forEach((line, index) => {\r\n const isLast = index === stackLines.length - 1;\r\n const char = isLast ? TREE_CHARS.last : TREE_CHARS.branch;\r\n lines.push(` ${COLORS.dim}${char} ${line.trim()}${COLORS.reset}`);\r\n });\r\n }\r\n } else {\r\n lines.push(` ${TREE_CHARS.last} ${COLORS.red}${String(error)}${COLORS.reset}`);\r\n }\r\n\r\n return lines;\r\n}\r\n","import { Agent } from \"../agent/Agent.js\";\r\nimport { ILogger } from \"./index.js\";\r\n\r\n/**\r\n * AgentLogger binds to Agent events and formats them for logging\r\n * \r\n * This class is responsible for:\r\n * - Listening to agent lifecycle events\r\n * - Formatting event data into structured logs\r\n * - Delegating actual logging to an ILogger implementation\r\n */\r\nexport class AgentLogger {\r\n constructor(\r\n private agent: Agent,\r\n private logger: ILogger\r\n ) {\r\n this.bindEvents();\r\n }\r\n\r\n private bindEvents() {\r\n // Debug Events (Verbose details)\r\n this.agent.on(\"agent:llm:call\", (event) => {\r\n const { data, trace } = event;\r\n this.logger.debug(`LLM Call #${data.step}`, {\r\n \"Messages\": data.messages.length,\r\n \"Tools Available\": data.tools?.length || 0,\r\n }, data.agentName, \"agent\", trace);\r\n });\r\n\r\n this.agent.on(\"agent:llm:response\", (event) => {\r\n const { data, trace } = event;\r\n const usage = data.usage\r\n ? `${data.usage.promptTokens} prompt + ${data.usage.completionTokens} completion = ${data.usage.totalTokens} total`\r\n : \"N/A\";\r\n\r\n const meta: Record<string, any> = {\r\n \"Tokens\": usage,\r\n \"Tool Calls\": data.toolCalls?.length || 0,\r\n };\r\n\r\n // Show content if present\r\n if (data.content) {\r\n meta[\"Content\"] = data.content;\r\n }\r\n\r\n // Show tool calls details if present\r\n if (data.toolCalls && data.toolCalls.length > 0) {\r\n data.toolCalls.forEach((tc, idx) => {\r\n meta[`Tool ${idx + 1}`] = `${tc.function.name}(${tc.function.arguments})`;\r\n });\r\n }\r\n\r\n this.logger.debug(`LLM Response (Step ${data.step})`, meta, data.agentName, \"agent\", trace);\r\n });\r\n\r\n this.agent.on(\"agent:tool:result\", (event) => {\r\n const { data, trace } = event;\r\n const status = data.error ? \"❌ Failed\" : \"✓ Success\";\r\n const meta: Record<string, any> = {\r\n \"Duration\": `${data.durationMs}ms`,\r\n };\r\n\r\n // Show output or error\r\n if (data.error) {\r\n meta[\"Error\"] = data.error;\r\n } else {\r\n meta[\"Output\"] = typeof data.output === \"string\"\r\n ? data.output\r\n : JSON.stringify(data.output);\r\n }\r\n\r\n this.logger.debug(`Tool Result: ${data.toolName} ${status}`, meta, data.agentName, \"agent\", trace);\r\n });\r\n\r\n // Info Events (High Level Flow)\r\n this.agent.on(\"agent:execution:start\", (event) => {\r\n const { data, trace, correlationId } = event;\r\n // Note: provider/model info is now in llm:call, but we can log generic start\r\n this.logger.info(`Execution Started`, {\r\n \"CorrelationId\": correlationId,\r\n \"Input\": data.input\r\n }, data.agentName, \"agent\", trace);\r\n });\r\n\r\n this.agent.on(\"agent:execution:end\", (event) => {\r\n const { data, trace } = event;\r\n const duration = (data.durationMs / 1000).toFixed(2) + \"s\";\r\n const usage = data.usage\r\n ? `${data.usage.totalTokens} tokens (${data.usage.promptTokens} prompt + ${data.usage.completionTokens} completion${data.usage.reasoningTokens ? ` + ${data.usage.reasoningTokens} reasoning` : \"\"})`\r\n : \"N/A\";\r\n\r\n this.logger.info(`Execution Finished ${data.status === \"success\" ? \"✓\" : (data.status === \"truncated\" ? \"⚠\" : \"❌\")}`, {\r\n \"Duration\": duration,\r\n \"Usage\": usage,\r\n }, data.agentName, \"agent\", trace);\r\n });\r\n\r\n this.agent.on(\"agent:tool:call\", (event) => {\r\n const { data, trace } = event;\r\n // Parse input if it's a JSON string for better readability\r\n let parsedInput = data.args;\r\n if (typeof data.args === \"string\") {\r\n try {\r\n parsedInput = JSON.parse(data.args);\r\n } catch {\r\n parsedInput = data.args;\r\n }\r\n }\r\n\r\n this.logger.info(`Tool Call: ${data.toolName}`, {\r\n \"Input\": typeof parsedInput === \"string\" ? parsedInput : JSON.stringify(parsedInput),\r\n }, data.agentName, \"agent\", trace);\r\n });\r\n\r\n // Error Events\r\n this.agent.on(\"agent:execution:error\", (event) => {\r\n const { data, trace } = event;\r\n this.logger.error(\r\n `Execution Error`,\r\n data.error, // Pass the sanitized error object\r\n data.agentName,\r\n \"agent\",\r\n trace\r\n );\r\n });\r\n }\r\n}\r\n","import { Workflow } from \"../workflow/Workflow.js\";\r\nimport { ILogger } from \"./index.js\";\r\n\r\n/**\r\n * WorkflowLogger binds to Workflow events and formats them for logging\r\n * \r\n * This class is responsible for:\r\n * - Listening to workflow lifecycle events\r\n * - Formatting event data into structured logs\r\n * - Delegating actual logging to an ILogger implementation\r\n */\r\nexport class WorkflowLogger {\r\n constructor(\r\n private workflow: Workflow,\r\n private logger: ILogger\r\n ) {\r\n this.bindEvents();\r\n }\r\n\r\n private bindEvents() {\r\n const workflowName = this.workflow.name || this.workflow.id;\r\n\r\n // Debug Events (Verbose details)\r\n this.workflow.on(\"workflow:step\", (event) => {\r\n const { data, trace } = event;\r\n \r\n if (data.status === \"running\") {\r\n this.logger.debug(`Step Started: ${data.stepName || data.nodeId}`, {\r\n \"Node ID\": data.nodeId,\r\n }, workflowName, \"workflow\", trace);\r\n } else if (data.status === \"success\") {\r\n const duration = data.durationMs ? (data.durationMs / 1000).toFixed(2) + \"s\" : \"N/A\";\r\n this.logger.debug(`Step Completed: ${data.stepName || data.nodeId}`, {\r\n \"Duration\": duration,\r\n }, workflowName, \"workflow\", trace);\r\n } else if (data.status === \"error\") {\r\n const duration = data.durationMs ? (data.durationMs / 1000).toFixed(2) + \"s\" : \"N/A\";\r\n this.logger.warn(`Step Failed: ${data.stepName || data.nodeId}`, {\r\n \"Duration\": duration,\r\n \"Error\": data.error?.message\r\n }, workflowName, \"workflow\", trace);\r\n }\r\n });\r\n\r\n // Info Events (High Level Flow)\r\n this.workflow.on(\"workflow:execution:start\", (event) => {\r\n const { data, trace, runId } = event;\r\n this.logger.info(`Execution Started`, {\r\n \"Workflow ID\": data.workflowId,\r\n \"Execution ID\": runId,\r\n \"Input\": typeof data.input === \"string\" ? data.input : JSON.stringify(data.input),\r\n }, workflowName, \"workflow\", trace);\r\n });\r\n\r\n this.workflow.on(\"workflow:execution:end\", (event) => {\r\n const { data, trace } = event;\r\n const duration = (data.durationMs / 1000).toFixed(2) + \"s\";\r\n this.logger.info(`Execution Completed ${data.status === \"success\" ? \"✓\" : \"❌\"}`, {\r\n \"Duration\": duration,\r\n \"Status\": data.status,\r\n \"Output\": typeof data.output === \"string\" ? data.output : JSON.stringify(data.output),\r\n }, workflowName, \"workflow\", trace);\r\n });\r\n\r\n // Error Events\r\n this.workflow.on(\"workflow:execution:error\", (event) => {\r\n const { data, trace } = event;\r\n this.logger.error(\r\n `Execution Error`,\r\n data.error,\r\n workflowName,\r\n \"workflow\",\r\n trace\r\n );\r\n });\r\n }\r\n}\r\n","import { formatLogLine, formatMetadata, formatError } from \"./formatters.js\";\r\nimport type { TraceContext } from \"../events/schemas.js\";\r\n\r\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\r\n\r\n// Re-export formatters and styles for extensibility\r\nexport * from \"./formatters.js\";\r\nexport * from \"./styles.js\";\r\nexport { AgentLogger } from \"./agent-logger.js\";\r\nexport { WorkflowLogger } from \"./workflow-logger.js\";\r\n\r\n/**\r\n * Logger interface\r\n * All loggers must implement these methods\r\n */\r\nexport interface ILogger {\r\n debug(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void;\r\n info(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void;\r\n warn(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void;\r\n error(message: string, error?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void;\r\n}\r\n\r\nconst LEVEL_WEIGHTS: Record<LogLevel, number> = {\r\n debug: 0,\r\n info: 1,\r\n warn: 2,\r\n error: 3,\r\n none: 4,\r\n};\r\n\r\n/**\r\n * Console-based logger implementation\r\n * Formats logs with colors, tree structure, and proper timestamps\r\n */\r\nexport class ConsoleLogger implements ILogger {\r\n constructor(private minLevel: LogLevel = \"info\") { }\r\n\r\n private shouldLog(level: LogLevel): boolean {\r\n return LEVEL_WEIGHTS[level] >= LEVEL_WEIGHTS[this.minLevel];\r\n }\r\n\r\n debug(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void {\r\n if (!this.shouldLog(\"debug\")) return;\r\n\r\n const mainLine = formatLogLine(\"debug\", entityName || null, message, entityType || null, trace);\r\n console.debug(mainLine);\r\n\r\n if (meta && typeof meta === \"object\" && Object.keys(meta).length > 0) {\r\n const metaLines = formatMetadata(meta);\r\n metaLines.forEach(line => console.debug(line));\r\n }\r\n }\r\n\r\n info(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void {\r\n if (!this.shouldLog(\"info\")) return;\r\n\r\n const mainLine = formatLogLine(\"info\", entityName || null, message, entityType || null, trace);\r\n console.info(mainLine);\r\n\r\n if (meta && typeof meta === \"object\" && Object.keys(meta).length > 0) {\r\n const metaLines = formatMetadata(meta);\r\n metaLines.forEach(line => console.info(line));\r\n }\r\n }\r\n\r\n warn(message: string, meta?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void {\r\n if (!this.shouldLog(\"warn\")) return;\r\n\r\n const mainLine = formatLogLine(\"warn\", entityName || null, message, entityType || null, trace);\r\n console.warn(mainLine);\r\n\r\n if (meta && typeof meta === \"object\" && Object.keys(meta).length > 0) {\r\n const metaLines = formatMetadata(meta);\r\n metaLines.forEach(line => console.warn(line));\r\n }\r\n }\r\n\r\n error(message: string, error?: any, entityName?: string, entityType?: \"agent\" | \"workflow\", trace?: TraceContext): void {\r\n if (!this.shouldLog(\"error\")) return;\r\n\r\n const mainLine = formatLogLine(\"error\", entityName || null, message, entityType || null, trace);\r\n console.error(mainLine);\r\n\r\n if (error) {\r\n const errorLines = formatError(error);\r\n errorLines.forEach(line => console.error(line));\r\n }\r\n }\r\n}\r\n","import { IModel, Message, ToolCall, TokenUsage, ToolDefinitionForLLM, StreamChunk, ProviderResponse } from \"./provider/index.js\";\r\nimport { IMemory } from \"./memory/index.js\";\r\nimport { Tool, ToolExecution } from \"./tools/index.js\";\r\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\r\nimport { IPIIMasker } from \"../lgpd/index.js\";\r\nimport { ILogger, LogLevel, ConsoleLogger } from \"../logger/index.js\";\r\nimport { AgentLogger } from \"../logger/agent-logger.js\";\r\nimport { Tracing } from \"../tracing/index.js\";\r\nimport { BaseAgent } from \"./BaseAgent.js\";\r\n\r\n// =============================================================================\r\n// Helper Types\r\n// =============================================================================\r\n\r\nexport interface IInstruction {\r\n resolve(): Promise<string>;\r\n}\r\n\r\nexport type AgentInstruction = string | IInstruction;\r\n\r\nexport interface AgentRequestContext {\r\n messages: Message[];\r\n tools: Tool[];\r\n}\r\n\r\nexport type RequestInterceptor = (context: AgentRequestContext) => Promise<AgentRequestContext>;\r\nexport type ResponseInterceptor = (response: ProviderResponse) => Promise<ProviderResponse>;\r\n\r\nexport type AgentConfig = {\r\n name: string;\r\n model: IModel;\r\n memory: IMemory;\r\n instructions: AgentInstruction;\r\n tools?: Tool[];\r\n maxSteps?: number;\r\n piiMasker?: IPIIMasker;\r\n interceptors?: {\r\n request?: RequestInterceptor[];\r\n response?: ResponseInterceptor[];\r\n };\r\n logger?: ILogger;\r\n logLevel?: LogLevel;\r\n};\r\n\r\nexport type AgentExecuteOptions = {\r\n responseFormat?: { type: \"json\"; schema?: Record<string, any> };\r\n maxSteps?: number;\r\n disableTools?: boolean;\r\n};\r\n\r\nexport type AgentResult = {\r\n content: any;\r\n toolExecutions: ToolExecution[];\r\n toolCalls?: ToolCall[];\r\n llmCalls: number;\r\n totalDurationMs: number;\r\n truncated: boolean;\r\n};\r\n\r\nexport type AgentStreamChunk =\r\n | StreamChunk\r\n | { type: \"tool_result\"; toolCallId: string; result: any }\r\n | { type: \"error\"; error: any };\r\n\r\nfunction generateCorrelationId(): string {\r\n return `exec_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n}\r\n\r\n// =============================================================================\r\n// Agent Class\r\n// =============================================================================\r\n\r\nexport class Agent extends BaseAgent {\r\n private resolvedInstructions?: string;\r\n private requestInterceptors: RequestInterceptor[] = [];\r\n private responseInterceptors: ResponseInterceptor[] = [];\r\n // @ts-ignore: used for side-effects (binding events)\r\n private loggerAdapter: AgentLogger;\r\n\r\n constructor(public config: AgentConfig) {\r\n super(config.name, config.piiMasker, config.memory);\r\n this.requestInterceptors = config.interceptors?.request || [];\r\n this.responseInterceptors = config.interceptors?.response || [];\r\n\r\n // Setup Logger\r\n const logger = config.logger || new ConsoleLogger(config.logLevel || \"error\");\r\n this.loggerAdapter = new AgentLogger(this, logger);\r\n }\r\n\r\n // ==========================================================================\r\n // Instructions\r\n // ==========================================================================\r\n\r\n private async resolveInstructions(): Promise<string> {\r\n if (this.resolvedInstructions !== undefined) return this.resolvedInstructions;\r\n\r\n if (typeof this.config.instructions === \"string\") {\r\n this.resolvedInstructions = this.config.instructions;\r\n return this.resolvedInstructions;\r\n }\r\n\r\n if (this.isInstruction(this.config.instructions)) {\r\n this.resolvedInstructions = await this.config.instructions.resolve();\r\n return this.resolvedInstructions;\r\n }\r\n\r\n return \"\";\r\n }\r\n\r\n private isInstruction(obj: any): obj is IInstruction {\r\n return obj && typeof obj.resolve === \"function\";\r\n }\r\n\r\n clearInstructionsCache(): void {\r\n this.resolvedInstructions = undefined;\r\n }\r\n\r\n // ==========================================================================\r\n // Memory\r\n // ==========================================================================\r\n\r\n async addMessage(message: Message): Promise<void> {\r\n this.memory = this.config.memory;\r\n await this.config.memory.addMessage(message);\r\n }\r\n\r\n private async getMessages(): Promise<Message[]> {\r\n const instructions = await this.resolveInstructions();\r\n const msgs = await this.config.memory.getMessages();\r\n\r\n // Ensure system prompt is present if instructions exist\r\n if (instructions && !msgs.some((m) => m.role === \"system\")) {\r\n msgs.unshift({ role: \"system\", content: instructions });\r\n }\r\n return msgs;\r\n }\r\n\r\n // ==========================================================================\r\n // Core execution\r\n // ==========================================================================\r\n\r\n async execute(options?: AgentExecuteOptions): Promise<AgentResult>;\r\n async execute(input?: string, options?: AgentExecuteOptions): Promise<AgentResult>;\r\n async execute(\r\n arg1: string | AgentExecuteOptions = {},\r\n arg2: AgentExecuteOptions = {}\r\n ): Promise<AgentResult> {\r\n const input = typeof arg1 === \"string\" ? arg1 : undefined;\r\n const options = typeof arg1 === \"string\" ? (arg2 ?? {}) : (arg1 ?? {});\r\n const startTime = Date.now();\r\n const correlationId = generateCorrelationId();\r\n const maxSteps = options.maxSteps ?? this.config.maxSteps ?? 10;\r\n\r\n const toolExecutions: ToolExecution[] = [];\r\n const collectedToolCalls: ToolCall[] = [];\r\n let llmCalls = 0;\r\n let truncated = false;\r\n let totalUsage: TokenUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\r\n\r\n // Start Telemetry Span for Agent Execution (canonical tracing)\r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `agent:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (agentSpan) => {\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input,\r\n },\r\n });\r\n\r\n try {\r\n if (input) {\r\n await this.addMessage({ role: \"user\", content: input });\r\n }\r\n let step = 0;\r\n while (step < maxSteps) {\r\n step++;\r\n llmCalls++;\r\n\r\n let messages = await this.getMessages();\r\n let tools = !options.disableTools && this.config.tools ? [...this.config.tools] : [];\r\n\r\n // Apply Request Interceptors\r\n let context: AgentRequestContext = { messages, tools };\r\n for (const interceptor of this.requestInterceptors) {\r\n context = await interceptor(context);\r\n }\r\n messages = context.messages;\r\n tools = context.tools;\r\n\r\n const llmTools = tools.length > 0\r\n ? tools.map(t => t.toLLMDefinition())\r\n : undefined;\r\n\r\n this.emit(\"agent:llm:call\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n step,\r\n messages,\r\n tools: llmTools,\r\n responseFormat: options.responseFormat,\r\n model: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n },\r\n },\r\n });\r\n\r\n const rawResponse = await Tracing.withSpan(\r\n {\r\n kind: \"llm\",\r\n name: `llm:step${step}`,\r\n correlationId,\r\n data: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n step,\r\n messagesCount: messages.length,\r\n toolsCount: llmTools?.length ?? 0,\r\n responseFormat: options.responseFormat,\r\n },\r\n },\r\n async (llmSpan) => {\r\n try {\r\n const resp = await this.config.model.generate(messages, llmTools, {\r\n responseFormat: options.responseFormat,\r\n });\r\n await llmSpan.end({\r\n status: \"success\",\r\n data: {\r\n usage: resp.usage,\r\n toolCallsCount: resp.toolCalls?.length ?? 0,\r\n outputPreview: typeof resp.content === \"string\" ? resp.content.substring(0, 200) : \"json_content\",\r\n },\r\n });\r\n return resp;\r\n } catch (e) {\r\n await llmSpan.end({ status: \"error\" });\r\n throw e;\r\n }\r\n }\r\n );\r\n\r\n let response = rawResponse;\r\n\r\n this.emit(\"agent:llm:response\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n step,\r\n content: response.content,\r\n toolCalls: response.toolCalls,\r\n usage: response.usage,\r\n model: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n },\r\n },\r\n });\r\n\r\n // Accumulate token usage\r\n if (response.usage) {\r\n totalUsage.promptTokens += response.usage.promptTokens;\r\n totalUsage.completionTokens += response.usage.completionTokens;\r\n totalUsage.totalTokens += response.usage.totalTokens;\r\n if (response.usage.reasoningTokens) {\r\n totalUsage.reasoningTokens = (totalUsage.reasoningTokens || 0) + response.usage.reasoningTokens;\r\n }\r\n }\r\n\r\n if (!response.toolCalls || response.toolCalls.length === 0 || options.disableTools) {\r\n // Apply Response Interceptors (Final Answer)\r\n for (const interceptor of this.responseInterceptors) {\r\n response = await interceptor(response);\r\n }\r\n\r\n await this.addMessage({ role: \"assistant\", content: response.content });\r\n\r\n await agentSpan.end({\r\n status: \"success\",\r\n data: {\r\n output: options.responseFormat?.type === \"json\"\r\n ? this.safeParseJson(response.content)\r\n : response.content,\r\n usage: totalUsage,\r\n },\r\n });\r\n\r\n return this.finishResult({\r\n correlationId,\r\n content: options.responseFormat?.type === \"json\"\r\n ? this.safeParseJson(response.content)\r\n : response.content,\r\n toolExecutions,\r\n toolCalls: options.disableTools ? response.toolCalls : undefined,\r\n llmCalls,\r\n totalDurationMs: Date.now() - startTime,\r\n truncated: false,\r\n totalUsage,\r\n });\r\n }\r\n\r\n // Add assistant message with tool calls before executing tools\r\n await this.addMessage({\r\n role: \"assistant\",\r\n content: response.content,\r\n tool_calls: response.toolCalls\r\n });\r\n\r\n for (const toolCall of response.toolCalls) {\r\n await Tracing.withSpan(\r\n {\r\n kind: \"tool\",\r\n name: `tool:${toolCall.function.name}`,\r\n correlationId,\r\n data: {\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n args: toolCall.function.arguments,\r\n },\r\n },\r\n async (toolSpan) => {\r\n this.emit(\"agent:tool:call\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n args: toolCall.function.arguments,\r\n },\r\n });\r\n\r\n const execution = await this.executeToolCall(toolCall);\r\n toolExecutions.push(execution);\r\n collectedToolCalls.push(toolCall);\r\n\r\n this.emit(\"agent:tool:result\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n output: execution.output,\r\n error: execution.error,\r\n durationMs: execution.durationMs,\r\n },\r\n });\r\n\r\n await toolSpan.end({\r\n status: execution.error ? \"error\" : \"success\",\r\n data: {\r\n output: execution.output,\r\n error: execution.error,\r\n },\r\n });\r\n\r\n await this.addMessage({\r\n role: \"tool\",\r\n tool_call_id: toolCall.id,\r\n content: execution.error ? `Error: ${execution.error}` : JSON.stringify(execution.output),\r\n });\r\n }\r\n );\r\n }\r\n }\r\n\r\n truncated = true;\r\n llmCalls++;\r\n // Final run after max steps (force answer)\r\n let finalMessages = await this.getMessages();\r\n let finalTools = !options.disableTools && this.config.tools ? [...this.config.tools] : [];\r\n\r\n // Interceptors for final run\r\n let context: AgentRequestContext = { messages: finalMessages, tools: finalTools };\r\n for (const interceptor of this.requestInterceptors) {\r\n context = await interceptor(context);\r\n }\r\n finalMessages = context.messages;\r\n // We ignore tools for final run usually, but keep consistency\r\n\r\n let finalResponse = await this.config.model.generate(finalMessages);\r\n\r\n // Response interceptors for final run\r\n for (const interceptor of this.responseInterceptors) {\r\n finalResponse = await interceptor(finalResponse);\r\n }\r\n\r\n await this.addMessage({ role: \"assistant\", content: finalResponse.content });\r\n\r\n await agentSpan.end({\r\n status: truncated ? \"cancelled\" : \"success\",\r\n data: {\r\n output: finalResponse.content,\r\n usage: totalUsage,\r\n },\r\n });\r\n\r\n return this.finishResult({\r\n correlationId,\r\n content: finalResponse.content,\r\n toolExecutions,\r\n toolCalls: collectedToolCalls,\r\n llmCalls,\r\n totalDurationMs: Date.now() - startTime,\r\n truncated,\r\n totalUsage,\r\n });\r\n\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new Error(String(err));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: error.message,\r\n stack: error.stack,\r\n name: error.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await agentSpan.end({ status: \"error\" });\r\n throw err;\r\n }\r\n }\r\n );\r\n }\r\n\r\n async *executeStream(options: AgentExecuteOptions = {}): AsyncGenerator<AgentStreamChunk> {\r\n const startTime = Date.now();\r\n const correlationId = generateCorrelationId();\r\n const maxSteps = options.maxSteps ?? this.config.maxSteps ?? 10;\r\n\r\n const toolExecutions: ToolExecution[] = [];\r\n const collectedToolCalls: ToolCall[] = [];\r\n let llmCalls = 0;\r\n let truncated = false;\r\n let totalUsage: TokenUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\r\n\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: undefined,\r\n },\r\n });\r\n\r\n try {\r\n let step = 0;\r\n while (step < maxSteps) {\r\n step++;\r\n llmCalls++;\r\n\r\n let messages = await this.getMessages();\r\n let tools = !options.disableTools && this.config.tools ? [...this.config.tools] : [];\r\n\r\n // Apply Request Interceptors\r\n let context: AgentRequestContext = { messages, tools };\r\n for (const interceptor of this.requestInterceptors) {\r\n context = await interceptor(context);\r\n }\r\n messages = context.messages;\r\n tools = context.tools;\r\n\r\n const llmTools = tools.length > 0\r\n ? tools.map(t => t.toLLMDefinition())\r\n : undefined;\r\n\r\n this.emit(\"agent:llm:call\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n step,\r\n messages,\r\n tools: llmTools,\r\n responseFormat: options.responseFormat,\r\n model: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n },\r\n },\r\n });\r\n\r\n const stream = this.config.model.generateStream(messages, llmTools, { responseFormat: options.responseFormat });\r\n\r\n let fullContent = \"\";\r\n let toolCallsBuffer: Record<number, { id: string; name: string; args: string }> = {};\r\n let chunkUsage: TokenUsage | undefined;\r\n\r\n for await (const chunk of stream) {\r\n yield chunk;\r\n\r\n if (chunk.type === \"content_delta\") {\r\n fullContent += chunk.delta;\r\n }\r\n else if (chunk.type === \"tool_call_start\") {\r\n toolCallsBuffer[chunk.index] = { id: chunk.id, name: chunk.name, args: \"\" };\r\n }\r\n else if (chunk.type === \"tool_call_delta\") {\r\n if (toolCallsBuffer[chunk.index]) {\r\n toolCallsBuffer[chunk.index].args += chunk.args;\r\n }\r\n }\r\n else if (chunk.type === \"finish\") {\r\n chunkUsage = chunk.usage;\r\n }\r\n }\r\n\r\n // Accumulate token usage\r\n if (chunkUsage) {\r\n totalUsage.promptTokens += chunkUsage.promptTokens;\r\n totalUsage.completionTokens += chunkUsage.completionTokens;\r\n totalUsage.totalTokens += chunkUsage.totalTokens;\r\n if (chunkUsage.reasoningTokens) {\r\n totalUsage.reasoningTokens = (totalUsage.reasoningTokens || 0) + chunkUsage.reasoningTokens;\r\n }\r\n }\r\n\r\n const toolCalls = Object.values(toolCallsBuffer).map(tc => ({\r\n id: tc.id,\r\n type: \"function\" as const,\r\n function: { name: tc.name, arguments: tc.args }\r\n }));\r\n\r\n this.emit(\"agent:llm:response\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n step,\r\n content: fullContent,\r\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\r\n usage: chunkUsage,\r\n model: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n },\r\n },\r\n });\r\n\r\n if (toolCalls.length === 0 || options.disableTools) {\r\n await this.addMessage({ role: \"assistant\", content: fullContent });\r\n\r\n // Emit execution:end event\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: \"success\",\r\n output: options.responseFormat?.type === \"json\"\r\n ? this.safeParseJson(fullContent)\r\n : fullContent,\r\n durationMs: Date.now() - startTime,\r\n usage: totalUsage,\r\n },\r\n });\r\n\r\n return;\r\n }\r\n\r\n await this.addMessage({ role: \"assistant\", content: fullContent || null, tool_calls: toolCalls });\r\n\r\n for (const toolCall of toolCalls) {\r\n const execution = await Tracing.withSpan(\r\n {\r\n kind: \"tool\",\r\n name: `tool:${toolCall.function.name}`,\r\n correlationId,\r\n data: {\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n args: toolCall.function.arguments,\r\n },\r\n },\r\n async (toolSpan) => {\r\n this.emit(\"agent:tool:call\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n args: toolCall.function.arguments,\r\n },\r\n });\r\n\r\n const exec = await this.executeToolCall(toolCall);\r\n toolExecutions.push(exec);\r\n collectedToolCalls.push(toolCall);\r\n\r\n this.emit(\"agent:tool:result\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n toolName: toolCall.function.name,\r\n toolCallId: toolCall.id,\r\n output: exec.output,\r\n error: exec.error,\r\n durationMs: exec.durationMs,\r\n },\r\n });\r\n\r\n await toolSpan.end({\r\n status: exec.error ? \"error\" : \"success\",\r\n data: { output: exec.output, error: exec.error },\r\n });\r\n\r\n return exec;\r\n }\r\n );\r\n\r\n yield {\r\n type: \"tool_result\",\r\n toolCallId: toolCall.id,\r\n result: execution.output\r\n };\r\n\r\n await this.addMessage({\r\n role: \"tool\",\r\n tool_call_id: toolCall.id,\r\n content: execution.error ? `Error: ${execution.error}` : JSON.stringify(execution.output),\r\n });\r\n }\r\n }\r\n\r\n // Max steps reached - do final non-stream call\r\n truncated = true;\r\n llmCalls++;\r\n\r\n let finalMessages = await this.getMessages();\r\n let finalTools = !options.disableTools && this.config.tools ? [...this.config.tools] : [];\r\n\r\n // Apply Request Interceptors for final call\r\n let finalContext: AgentRequestContext = { messages: finalMessages, tools: finalTools };\r\n for (const interceptor of this.requestInterceptors) {\r\n finalContext = await interceptor(finalContext);\r\n }\r\n finalMessages = finalContext.messages;\r\n\r\n const finalResponse = await this.config.model.generate(finalMessages);\r\n\r\n // Accumulate final usage\r\n if (finalResponse.usage) {\r\n totalUsage.promptTokens += finalResponse.usage.promptTokens;\r\n totalUsage.completionTokens += finalResponse.usage.completionTokens;\r\n totalUsage.totalTokens += finalResponse.usage.totalTokens;\r\n if (finalResponse.usage.reasoningTokens) {\r\n totalUsage.reasoningTokens = (totalUsage.reasoningTokens || 0) + finalResponse.usage.reasoningTokens;\r\n }\r\n }\r\n\r\n await this.addMessage({ role: \"assistant\", content: finalResponse.content });\r\n\r\n // Emit final result\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: truncated ? \"truncated\" : \"success\",\r\n output: finalResponse.content,\r\n durationMs: Date.now() - startTime,\r\n usage: totalUsage,\r\n },\r\n });\r\n\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new Error(String(err));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: error.message,\r\n stack: error.stack,\r\n name: error.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n yield { type: \"error\", error };\r\n }\r\n }\r\n\r\n // ==========================================================================\r\n // Tools Execution\r\n // ==========================================================================\r\n\r\n private async executeToolCall(toolCall: ToolCall): Promise<ToolExecution> {\r\n const startTime = Date.now();\r\n const toolName = toolCall.function.name;\r\n const tool = this.config.tools?.find((t) => t.id === toolName);\r\n\r\n if (!tool) {\r\n return {\r\n id: toolCall.id,\r\n name: toolName,\r\n input: toolCall.function.arguments,\r\n output: null,\r\n durationMs: Date.now() - startTime,\r\n error: `Tool '${toolName}' not found`,\r\n };\r\n }\r\n\r\n try {\r\n const output = await tool.execute({}, toolCall.function.arguments);\r\n return {\r\n id: toolCall.id,\r\n name: toolName,\r\n input: toolCall.function.arguments,\r\n output,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (error) {\r\n return {\r\n id: toolCall.id,\r\n name: toolName,\r\n input: toolCall.function.arguments,\r\n output: null,\r\n durationMs: Date.now() - startTime,\r\n error: error instanceof Error ? error.message : String(error),\r\n };\r\n }\r\n }\r\n\r\n // ==========================================================================\r\n // Helpers\r\n // ==========================================================================\r\n\r\n private safeParseJson(content: string | null): any {\r\n if (!content) return null;\r\n try {\r\n return JSON.parse(content);\r\n } catch {\r\n return content;\r\n }\r\n }\r\n\r\n private finishResult(params: {\r\n correlationId: string;\r\n content: any;\r\n toolExecutions: ToolExecution[];\r\n toolCalls?: ToolCall[];\r\n llmCalls: number;\r\n totalDurationMs: number;\r\n truncated: boolean;\r\n totalUsage?: TokenUsage;\r\n }): AgentResult {\r\n const result: AgentResult = {\r\n content: params.content,\r\n toolExecutions: params.toolExecutions,\r\n toolCalls: params.toolCalls,\r\n llmCalls: params.llmCalls,\r\n totalDurationMs: params.totalDurationMs,\r\n truncated: params.truncated,\r\n };\r\n\r\n this.emit(\"agent:execution:end\", {\r\n correlationId: params.correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: params.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n usage: params.totalUsage,\r\n durationMs: params.totalDurationMs,\r\n },\r\n });\r\n\r\n return result;\r\n }\r\n}\r\n","/**\r\n * Implementação básica em memória (padrão)\r\n */\r\n\r\nimport { IMemory } from \"./memory.js\";\r\nimport { Message } from \"../provider/index.js\";\r\n\r\nexport class InMemory implements IMemory {\r\n private messages: Message[] = [];\r\n\r\n constructor(private options: { maxMessages?: number } = {}) { }\r\n\r\n async addMessage(message: Message): Promise<void> {\r\n this.messages.push(message);\r\n\r\n // Truncate if needed (keep latest N messages)\r\n if (this.options.maxMessages && this.messages.length > this.options.maxMessages) {\r\n const systemMessage = this.messages.find(m => m.role === \"system\");\r\n const removeCount = this.messages.length - this.options.maxMessages;\r\n\r\n this.messages.splice(0, removeCount);\r\n\r\n // Restore system message if lost\r\n if (systemMessage && !this.messages.includes(systemMessage)) {\r\n this.messages.unshift(systemMessage);\r\n }\r\n }\r\n }\r\n\r\n async getMessages(): Promise<Message[]> {\r\n return [...this.messages];\r\n }\r\n\r\n async clear(): Promise<void> {\r\n this.messages = [];\r\n }\r\n}\r\n\r\n","// ... imports ...\r\nimport { z, ZodSchema } from \"zod\";\r\nimport { ToolDefinitionForLLM } from \"../provider/index.js\";\r\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\r\n\r\n// Helper to convert Zod/JSON schema to OpenAI format\r\nfunction toJsonSchema(input: unknown): Record<string, any> {\r\n const defaultSchema = { type: \"object\", properties: {}, required: [] };\r\n\r\n if (input && typeof input === \"object\" && \"_def\" in input) {\r\n try {\r\n const schema = zodToJsonSchema(input as any, {\r\n $refStrategy: \"none\",\r\n target: \"openApi3\",\r\n }) as Record<string, unknown>;\r\n return {\r\n type: \"object\",\r\n properties: (schema.properties as Record<string, unknown>) ?? {},\r\n required: (schema.required as string[]) ?? [],\r\n };\r\n } catch {\r\n return defaultSchema;\r\n }\r\n }\r\n\r\n if (input && typeof input === \"object\" && \"type\" in input) {\r\n const obj = input as Record<string, unknown>;\r\n return {\r\n type: \"object\",\r\n properties: (obj.properties as Record<string, unknown>) ?? {},\r\n required: (obj.required as string[]) ?? [],\r\n };\r\n }\r\n\r\n return defaultSchema;\r\n}\r\n\r\nexport type ToolConfig<Input = any, Output = any> = {\r\n id: string;\r\n description?: string;\r\n inputSchema?: ZodSchema<Input>;\r\n handler?: (ctx: any, input: Input) => Promise<Output>;\r\n};\r\n\r\nexport type ToolExecution = {\r\n id: string;\r\n name: string;\r\n input: any;\r\n output: any;\r\n durationMs: number;\r\n error?: string;\r\n};\r\n\r\nexport class Tool<Input = any, Output = any> {\r\n public readonly id: string;\r\n public readonly description?: string;\r\n public readonly inputSchema?: ZodSchema<Input>;\r\n private handler?: (ctx: any, input: Input) => Promise<Output>;\r\n\r\n constructor(config: ToolConfig<Input, Output>) {\r\n this.id = config.id;\r\n this.description = config.description;\r\n this.inputSchema = config.inputSchema;\r\n this.handler = config.handler;\r\n }\r\n\r\n /**\r\n * Converte a tool para o formato esperado pelo LLM\r\n */\r\n toLLMDefinition(): ToolDefinitionForLLM {\r\n return {\r\n type: \"function\",\r\n function: {\r\n name: this.id,\r\n description: this.description,\r\n parameters: this.inputSchema ? toJsonSchema(this.inputSchema) : undefined,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Executa a tool com validação de input\r\n */\r\n async execute(context: any, input: any): Promise<Output> {\r\n let parsedInput = input;\r\n\r\n // Validate input if schema is present\r\n if (this.inputSchema) {\r\n // If input is string (JSON), parse it first\r\n if (typeof input === \"string\") {\r\n try {\r\n parsedInput = JSON.parse(input);\r\n } catch {\r\n throw new Error(`Invalid JSON input for tool ${this.id}`);\r\n }\r\n }\r\n\r\n const result = this.inputSchema.safeParse(parsedInput);\r\n if (!result.success) {\r\n throw new Error(`Invalid input for tool ${this.id}: ${result.error.message}`);\r\n }\r\n parsedInput = result.data;\r\n }\r\n\r\n if (this.handler) {\r\n return this.handler(context, parsedInput);\r\n }\r\n \r\n throw new Error(`Tool ${this.id} has no handler implementation.`);\r\n }\r\n}\r\n","import { v4 as uuidv4 } from 'uuid';\r\nimport { setTimeout as sleep } from 'timers/promises';\r\nimport type { ZodSchema } from 'zod';\r\nimport { EventEmitter } from 'events';\r\nimport type { IWorkflowStateStore, IWorkflowQueue, RetryPolicy, WorkflowState } from './adapters';\r\nimport { calculateRetryDelay, isRetryableError } from './adapters';\r\nimport type { WorkflowEventMap, WorkflowEventName } from './events.js';\r\nimport { ConsoleLogger, WorkflowLogger } from '../logger/index.js';\r\nimport { Tracing } from '../tracing/index.js';\r\n\r\n// =============================================================================\r\n// Types\r\n// =============================================================================\r\n\r\nexport type StepContext<T = any> = {\r\n input: T;\r\n state: Record<string, any>;\r\n};\r\n\r\nexport type StepHandler<Input, Output> = (ctx: StepContext<Input>) => Promise<Output>;\r\n\r\nexport type StepDefinition<Input = any, Output = any> = {\r\n id: string;\r\n name: string;\r\n handler: StepHandler<Input, Output>;\r\n type: 'start' | 'standard' | 'branch' | 'parallel' | 'finish';\r\n branches?: Record<string, Workflow<any, any>>;\r\n parallelWorkflows?: Workflow<any, any>[];\r\n};\r\n\r\nexport interface WorkflowConfig<Input = any, Output = any> {\r\n id: string;\r\n name?: string;\r\n description?: string;\r\n inputSchema?: ZodSchema<Input>;\r\n outputSchema?: ZodSchema<Output>;\r\n maxSteps?: number;\r\n timeout?: number;\r\n stateStore?: IWorkflowStateStore;\r\n queueAdapter?: IWorkflowQueue;\r\n retryPolicy?: RetryPolicy;\r\n logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\r\n}\r\n\r\nexport type WorkflowStreamChunk =\r\n | { type: 'step_start'; step: string }\r\n | { type: 'step_end'; step: string; output: any };\r\n\r\n// =============================================================================\r\n// Workflow Class\r\n// =============================================================================\r\n\r\nexport class Workflow<Input = any, Output = any> {\r\n public readonly id: string;\r\n public readonly name?: string;\r\n public readonly description?: string;\r\n\r\n private config: WorkflowConfig<Input, Output>;\r\n private steps: StepDefinition[] = [];\r\n private hasStartStep = false;\r\n private hasFinishStep = false;\r\n private emitter = new EventEmitter();\r\n\r\n /**\r\n * Construtor compatível com assinatura antiga (string) e nova (config)\r\n */\r\n constructor(idOrConfig: string | WorkflowConfig<Input, Output>) {\r\n if (typeof idOrConfig === 'string') {\r\n this.config = { id: idOrConfig };\r\n } else {\r\n this.config = idOrConfig;\r\n }\r\n this.id = this.config.id;\r\n this.name = this.config.name;\r\n this.description = this.config.description;\r\n\r\n // Initialize logger if logLevel is provided\r\n if (this.config.logLevel && this.config.logLevel !== \"none\") {\r\n const logger = new ConsoleLogger(this.config.logLevel);\r\n new WorkflowLogger(this, logger);\r\n }\r\n }\r\n\r\n /**\r\n * start() - obrigatório se inputSchema existir\r\n */\r\n start<T = Input>(handler: StepHandler<Input, T>): Workflow<Input, Output> {\r\n if (this.hasStartStep) throw new Error('Workflow already has a start step');\r\n if (this.steps.length > 0) throw new Error('start() deve ser chamado antes dos steps');\r\n this.hasStartStep = true;\r\n this.steps.push({ id: uuidv4(), name: '__start__', handler, type: 'start' });\r\n return this;\r\n }\r\n\r\n /**\r\n * step() - step linear\r\n */\r\n step<StepInput, StepOutput>(\r\n name: string,\r\n handler: StepHandler<StepInput, StepOutput>,\r\n ): Workflow<Input, Output> {\r\n if (this.config.inputSchema && !this.hasStartStep) {\r\n throw new Error('start() deve ser chamado antes de step() quando há inputSchema');\r\n }\r\n if (this.hasFinishStep) throw new Error('Não é possível adicionar steps após finish()');\r\n\r\n this.steps.push({ id: uuidv4(), name, handler, type: 'standard' });\r\n return this;\r\n }\r\n\r\n then<StepInput, StepOutput>(\r\n name: string,\r\n handler: StepHandler<StepInput, StepOutput>,\r\n ): Workflow<Input, Output> {\r\n return this.step(name, handler);\r\n }\r\n\r\n /**\r\n * branch() - retorna chave do branch\r\n */\r\n branch<StepInput>(\r\n name: string,\r\n handler: StepHandler<StepInput, string>,\r\n branches: Record<string, (wf: Workflow<StepInput, any>) => void>,\r\n ): Workflow<Input, Output> {\r\n if (this.hasFinishStep) throw new Error('Não é possível adicionar steps após finish()');\r\n\r\n const branchWorkflows: Record<string, Workflow<StepInput, any>> = {};\r\n for (const [key, config] of Object.entries(branches)) {\r\n const branchWf = new Workflow<StepInput, any>({ id: `${this.id}-branch-${key}` });\r\n config(branchWf);\r\n branchWorkflows[key] = branchWf;\r\n }\r\n\r\n this.steps.push({\r\n id: uuidv4(),\r\n name,\r\n handler,\r\n type: 'branch',\r\n branches: branchWorkflows,\r\n });\r\n return this;\r\n }\r\n\r\n /**\r\n * parallel() - executa workflows em paralelo\r\n */\r\n parallel<StepInput>(\r\n name: string,\r\n workflows: ((wf: Workflow<StepInput, any>) => void)[],\r\n ): Workflow<Input, Output> {\r\n if (this.hasFinishStep) throw new Error('Não é possível adicionar steps após finish()');\r\n\r\n const parallelWfs = workflows.map((config, index) => {\r\n const wf = new Workflow<StepInput, any>({ id: `${this.id}-parallel-${index}` });\r\n config(wf);\r\n return wf;\r\n });\r\n\r\n this.steps.push({\r\n id: uuidv4(),\r\n name,\r\n handler: async ({ input }) => input,\r\n type: 'parallel',\r\n parallelWorkflows: parallelWfs,\r\n });\r\n return this;\r\n }\r\n\r\n /**\r\n * finish() - obrigatório se outputSchema existir\r\n */\r\n finish(handler: StepHandler<any, Output>): Workflow<Input, Output> {\r\n if (this.hasFinishStep) throw new Error('Workflow already has a finish step');\r\n this.hasFinishStep = true;\r\n this.steps.push({ id: uuidv4(), name: '__finish__', handler, type: 'finish' });\r\n return this;\r\n }\r\n\r\n // =============================================================================\r\n // Event Methods (Composition over Inheritance)\r\n // =============================================================================\r\n\r\n on<E extends WorkflowEventName>(event: E, listener: (data: WorkflowEventMap[E]) => void): this {\r\n this.emitter.on(event, listener);\r\n return this;\r\n }\r\n\r\n once<E extends WorkflowEventName>(event: E, listener: (data: WorkflowEventMap[E]) => void): this {\r\n this.emitter.once(event, listener);\r\n return this;\r\n }\r\n\r\n off<E extends WorkflowEventName>(event: E, listener: (data: WorkflowEventMap[E]) => void): this {\r\n this.emitter.off(event, listener);\r\n return this;\r\n }\r\n\r\n private emit<E extends WorkflowEventName>(\r\n event: E,\r\n payload: {\r\n data: WorkflowEventMap[E][\"data\"];\r\n correlationId?: string;\r\n runId?: string;\r\n }\r\n ): void {\r\n const traceContext = Tracing.getContext();\r\n const fullEvent = {\r\n type: event,\r\n timestamp: new Date().toISOString(),\r\n trace: {\r\n traceId: traceContext?.traceId || `fallback-${Date.now()}`,\r\n spanId: traceContext?.spanId || `fallback-${Date.now()}`,\r\n parentSpanId: traceContext?.parentId,\r\n },\r\n correlationId: payload.correlationId,\r\n runId: payload.runId,\r\n data: payload.data,\r\n };\r\n this.emitter.emit(event, fullEvent);\r\n }\r\n\r\n // =============================================================================\r\n // Execution\r\n // =============================================================================\r\n\r\n /**\r\n * Execução síncrona\r\n */\r\n async run(input: Input, options?: { executionId?: string }): Promise<Output> {\r\n if (this.config.outputSchema && !this.hasFinishStep) {\r\n throw new Error('finish() deve ser chamado quando há outputSchema');\r\n }\r\n\r\n // Validação de input\r\n if (this.config.inputSchema) {\r\n const parsed = this.config.inputSchema.safeParse(input);\r\n if (!parsed.success) {\r\n throw new Error(`Input validation failed: ${parsed.error.message}`);\r\n }\r\n }\r\n\r\n const executionId = options?.executionId || uuidv4();\r\n const startTime = Date.now();\r\n let currentInput: any = input;\r\n const state: Record<string, any> = {};\r\n\r\n // Start Telemetry Span for Workflow Execution (canonical tracing)\r\n return Tracing.withSpan(\r\n {\r\n kind: \"workflow\",\r\n name: `workflow:${this.id}`,\r\n runId: executionId,\r\n data: { workflowId: this.id, input },\r\n },\r\n async (workflowSpan) => {\r\n this.emit(\"workflow:execution:start\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n input,\r\n },\r\n });\r\n\r\n if (this.config.stateStore) {\r\n await this.saveState(executionId, {\r\n workflowId: this.id,\r\n executionId,\r\n status: 'running',\r\n currentStep: 0,\r\n stepStates: {},\r\n input,\r\n startedAt: new Date(),\r\n updatedAt: new Date(),\r\n });\r\n }\r\n\r\n try {\r\n let stepIndex = 0;\r\n for (const step of this.steps) {\r\n const result = await Tracing.withSpan(\r\n {\r\n kind: \"workflow\",\r\n name: `workflow:step:${step.name}`,\r\n runId: executionId,\r\n data: { workflowId: this.id, input: currentInput, stepName: step.name },\r\n },\r\n async (stepSpan) => {\r\n try {\r\n const out = await this.executeStepWithRetry(executionId, step, currentInput, state);\r\n await stepSpan.end({ status: \"success\", data: { output: out } });\r\n return out;\r\n } catch (e) {\r\n await stepSpan.end({ status: \"error\" });\r\n throw e;\r\n }\r\n }\r\n );\r\n\r\n if (step.type === 'start' || step.type === 'standard') {\r\n currentInput = result;\r\n state[step.name] = result;\r\n } else if (step.type === 'branch') {\r\n const branchKey = result as string;\r\n const branchWf = step.branches?.[branchKey];\r\n if (branchWf) {\r\n const branchResult = await branchWf.run(currentInput);\r\n currentInput = branchResult;\r\n state[step.name] = branchKey;\r\n state[branchKey] = branchResult;\r\n }\r\n } else if (step.type === 'parallel') {\r\n if (step.parallelWorkflows) {\r\n const results = await Promise.all(step.parallelWorkflows.map((wf) => wf.run(currentInput)));\r\n currentInput = results;\r\n state[step.name] = results;\r\n }\r\n } else if (step.type === 'finish') {\r\n currentInput = result;\r\n }\r\n\r\n if (this.config.stateStore) {\r\n await this.saveState(executionId, {\r\n workflowId: this.id,\r\n executionId,\r\n status: 'running',\r\n currentStep: stepIndex,\r\n stepStates: { ...state },\r\n input,\r\n startedAt: new Date(),\r\n updatedAt: new Date(),\r\n });\r\n }\r\n\r\n stepIndex++;\r\n }\r\n\r\n const output = currentInput as Output;\r\n\r\n if (this.config.outputSchema) {\r\n const parsed = this.config.outputSchema.safeParse(output);\r\n if (!parsed.success) {\r\n throw new Error(`Output validation failed: ${parsed.error.message}`);\r\n }\r\n }\r\n\r\n if (this.config.stateStore) {\r\n await this.saveState(executionId, {\r\n workflowId: this.id,\r\n executionId,\r\n status: 'completed',\r\n currentStep: this.steps.length,\r\n stepStates: state,\r\n input,\r\n output,\r\n startedAt: new Date(),\r\n updatedAt: new Date(),\r\n completedAt: new Date(),\r\n });\r\n }\r\n\r\n this.emit(\"workflow:execution:end\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n status: \"success\",\r\n output,\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n\r\n await workflowSpan.end({ status: \"success\", data: { output } });\r\n return output;\r\n } catch (error) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n\r\n this.emit(\"workflow:execution:error\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n\r\n if (this.config.stateStore) {\r\n await this.saveState(executionId, {\r\n workflowId: this.id,\r\n executionId,\r\n status: 'failed',\r\n currentStep: 0,\r\n stepStates: state,\r\n input,\r\n startedAt: new Date(),\r\n updatedAt: new Date(),\r\n completedAt: new Date(),\r\n error: error instanceof Error ? error.message : String(error),\r\n });\r\n }\r\n await workflowSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private async executeStepWithRetry(\r\n executionId: string,\r\n step: StepDefinition,\r\n currentInput: any,\r\n state: Record<string, any>,\r\n ): Promise<any> {\r\n const stepStartTime = Date.now();\r\n\r\n this.emit(\"workflow:step\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n nodeId: step.id,\r\n stepName: step.name,\r\n status: \"running\",\r\n },\r\n });\r\n\r\n const policy = this.config.retryPolicy;\r\n\r\n if (!policy) {\r\n try {\r\n const result = await step.handler({ input: currentInput, state });\r\n this.emit(\"workflow:step\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n nodeId: step.id,\r\n stepName: step.name,\r\n status: \"success\",\r\n durationMs: Date.now() - stepStartTime,\r\n },\r\n });\r\n return result;\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new Error(String(err));\r\n this.emit(\"workflow:step\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n nodeId: step.id,\r\n stepName: step.name,\r\n status: \"error\",\r\n error: {\r\n message: error.message,\r\n stack: error.stack,\r\n name: error.name,\r\n },\r\n durationMs: Date.now() - stepStartTime,\r\n },\r\n });\r\n throw error;\r\n }\r\n }\r\n\r\n let lastError: Error | undefined;\r\n for (let attempt = 1; attempt <= policy.maxAttempts; attempt++) {\r\n try {\r\n const result = await step.handler({ input: currentInput, state });\r\n this.emit(\"workflow:step\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n nodeId: step.id,\r\n stepName: step.name,\r\n status: \"success\",\r\n durationMs: Date.now() - stepStartTime,\r\n },\r\n });\r\n return result;\r\n } catch (err) {\r\n lastError = err instanceof Error ? err : new Error(String(err));\r\n\r\n if (!isRetryableError(lastError, policy) || attempt >= policy.maxAttempts) {\r\n this.emit(\"workflow:step\", {\r\n runId: executionId,\r\n data: {\r\n workflowId: this.id,\r\n nodeId: step.id,\r\n stepName: step.name,\r\n status: \"error\",\r\n error: {\r\n message: lastError.message,\r\n stack: lastError.stack,\r\n name: lastError.name,\r\n },\r\n durationMs: Date.now() - stepStartTime,\r\n },\r\n });\r\n throw lastError;\r\n }\r\n\r\n const delay = calculateRetryDelay(policy, attempt);\r\n // Note: Retry events are not explicitly in the new unified schema for now, \r\n // but 'workflow:step' with 'error' effectively logs the failure of an attempt.\r\n // We could add a 'metadata' field to indicate retry attempt if needed.\r\n \r\n await sleep(delay);\r\n }\r\n }\r\n throw lastError;\r\n }\r\n\r\n private async saveState(executionId: string, state: WorkflowState): Promise<void> {\r\n if (this.config.stateStore) {\r\n await this.config.stateStore.save(executionId, state);\r\n }\r\n }\r\n\r\n /**\r\n * Enfileira execução assíncrona (requer queueAdapter)\r\n */\r\n async enqueue(input: Input): Promise<{ executionId: string }> {\r\n if (!this.config.queueAdapter) {\r\n throw new Error('Queue adapter não configurado. Não é possível enfileirar.');\r\n }\r\n\r\n if (this.config.inputSchema) {\r\n const parsed = this.config.inputSchema.safeParse(input);\r\n if (!parsed.success) {\r\n throw new Error(`Input validation failed: ${parsed.error.message}`);\r\n }\r\n }\r\n\r\n const executionId = uuidv4();\r\n\r\n if (this.config.stateStore) {\r\n await this.saveState(executionId, {\r\n workflowId: this.id,\r\n executionId,\r\n status: 'pending',\r\n currentStep: 0,\r\n stepStates: {},\r\n input,\r\n startedAt: new Date(),\r\n updatedAt: new Date(),\r\n });\r\n }\r\n\r\n const firstStep = this.steps[0];\r\n if (firstStep) {\r\n await this.config.queueAdapter.enqueue({\r\n executionId,\r\n workflowId: this.id,\r\n stepId: firstStep.id,\r\n stepName: firstStep.name,\r\n input,\r\n attempt: 1,\r\n createdAt: new Date(),\r\n });\r\n }\r\n\r\n return { executionId };\r\n }\r\n\r\n /**\r\n * Consulta status (requer queueAdapter ou stateStore)\r\n */\r\n async getStatus(executionId: string): Promise<{\r\n status: WorkflowState['status'];\r\n currentStep?: string;\r\n progress?: number;\r\n }> {\r\n if (this.config.queueAdapter?.getStatus) {\r\n return this.config.queueAdapter.getStatus(executionId);\r\n }\r\n\r\n if (this.config.stateStore) {\r\n const state = await this.config.stateStore.load(executionId);\r\n if (!state) throw new Error(`Execution ${executionId} not found`);\r\n return {\r\n status: state.status,\r\n currentStep: this.steps[state.currentStep]?.name,\r\n progress: this.steps.length ? state.currentStep / this.steps.length : 0,\r\n };\r\n }\r\n\r\n throw new Error('Queue adapter ou state store necessário para getStatus()');\r\n }\r\n}\r\n","/**\r\n * Workflow Adapters - Interfaces for State and Queue management\r\n */\r\n\r\nexport interface WorkflowState {\r\n workflowId: string;\r\n executionId: string;\r\n status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';\r\n currentStep: number;\r\n stepStates: Record<string, any>;\r\n input: any;\r\n output?: any;\r\n startedAt: Date;\r\n updatedAt: Date;\r\n completedAt?: Date;\r\n error?: string;\r\n retryCount?: number;\r\n}\r\n\r\nexport interface IWorkflowStateStore {\r\n save(executionId: string, state: WorkflowState): Promise<void>;\r\n load(executionId: string): Promise<WorkflowState | null>;\r\n delete(executionId: string): Promise<void>;\r\n listActive(workflowId?: string): Promise<string[]>;\r\n}\r\n\r\nexport interface WorkflowJob {\r\n executionId: string;\r\n workflowId: string;\r\n stepId: string;\r\n stepName: string;\r\n input: any;\r\n attempt: number;\r\n createdAt: Date;\r\n}\r\n\r\nexport interface IWorkflowQueue {\r\n enqueue(job: WorkflowJob): Promise<void>;\r\n process(handler: (job: WorkflowJob) => Promise<void>): void;\r\n close(): Promise<void>;\r\n getStatus?(\r\n executionId: string,\r\n ): Promise<{ status: WorkflowState['status']; currentStep?: string; progress?: number }>;\r\n}\r\n\r\nexport interface RetryPolicy {\r\n maxAttempts: number;\r\n backoff: 'exponential' | 'linear' | 'fixed';\r\n initialDelay: number;\r\n maxDelay?: number;\r\n retryableErrors?: string[];\r\n}\r\n\r\nexport function calculateRetryDelay(policy: RetryPolicy, attempt: number): number {\r\n const { backoff, initialDelay, maxDelay = 60000 } = policy;\r\n let delay: number;\r\n switch (backoff) {\r\n case 'exponential':\r\n delay = initialDelay * Math.pow(2, attempt - 1);\r\n break;\r\n case 'linear':\r\n delay = initialDelay * attempt;\r\n break;\r\n case 'fixed':\r\n default:\r\n delay = initialDelay;\r\n }\r\n return Math.min(delay, maxDelay);\r\n}\r\n\r\nexport function isRetryableError(error: Error, policy: RetryPolicy): boolean {\r\n if (!policy.retryableErrors || policy.retryableErrors.length === 0) {\r\n return true;\r\n }\r\n return policy.retryableErrors.some(\r\n (pattern) => error.message.includes(pattern) || error.name.includes(pattern),\r\n );\r\n}\r\n\r\n","import { z } from \"zod\";\r\n\r\n// =============================================================================\r\n// Common Fields\r\n// =============================================================================\r\n\r\nexport const TraceContextSchema = z.object({\r\n traceId: z.string().describe(\"Unique identifier for the trace\"),\r\n spanId: z.string().describe(\"Unique identifier for the current span\"),\r\n parentSpanId: z.string().optional().describe(\"Identifier of the parent span, if any\"),\r\n});\r\n\r\nexport const EventCommonSchema = z.object({\r\n type: z.string().describe(\"Event type identifier (e.g., 'agent:execution:start')\"),\r\n timestamp: z.string().datetime().describe(\"ISO 8601 timestamp of when the event occurred\"),\r\n trace: TraceContextSchema,\r\n correlationId: z.string().optional().describe(\"Optional external correlation ID\"),\r\n runId: z.string().optional().describe(\"Logical execution run ID\"),\r\n});\r\n\r\nexport const UsageSchema = z.object({\r\n promptTokens: z.number(),\r\n completionTokens: z.number(),\r\n totalTokens: z.number(),\r\n reasoningTokens: z.number().optional(),\r\n});\r\n\r\nexport const ErrorSchema = z.object({\r\n name: z.string().optional(),\r\n message: z.string(),\r\n code: z.string().optional(),\r\n stack: z.string().optional(),\r\n details: z.any().optional(),\r\n});\r\n\r\nexport const ModelSchema = z.object({\r\n provider: z.string(),\r\n model: z.string(),\r\n temperature: z.number().optional(),\r\n maxTokens: z.number().optional(),\r\n topP: z.number().optional(),\r\n frequencyPenalty: z.number().optional(),\r\n presencePenalty: z.number().optional(),\r\n}).passthrough(); // Allow any other provider-specific config\r\n\r\n// =============================================================================\r\n// Agent Events\r\n// =============================================================================\r\n\r\nexport const AgentExecutionStartSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:execution:start\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n input: z.any().optional().describe(\"Input arguments for the execution\"),\r\n metadata: z.record(z.any()).optional(),\r\n }),\r\n});\r\n\r\nexport const AgentExecutionEndSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:execution:end\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n status: z.enum([\"success\", \"error\", \"truncated\"]),\r\n output: z.any().optional().describe(\"Final output of the execution\"),\r\n durationMs: z.number(),\r\n usage: UsageSchema.optional().describe(\"Total token usage for this execution\"),\r\n }),\r\n});\r\n\r\nexport const AgentExecutionErrorSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:execution:error\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n error: ErrorSchema,\r\n durationMs: z.number().optional(),\r\n }),\r\n});\r\n\r\nexport const AgentLLMCallSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:llm:call\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n step: z.number().int().positive().describe(\"Current execution step\"),\r\n model: ModelSchema,\r\n messages: z.array(z.any()).describe(\"Messages sent to the LLM\"),\r\n tools: z.array(z.any()).optional().describe(\"Tools definitions sent to the LLM\"),\r\n responseFormat: z.any().optional(),\r\n }),\r\n});\r\n\r\nexport const AgentLLMResponseSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:llm:response\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n step: z.number().int().positive(),\r\n model: ModelSchema,\r\n content: z.any().describe(\"Content returned by the LLM\"),\r\n toolCalls: z.array(z.any()).optional(),\r\n finishReason: z.string().optional(),\r\n usage: UsageSchema.optional(),\r\n durationMs: z.number().optional(),\r\n }),\r\n});\r\n\r\nexport const AgentToolCallSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:tool:call\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n toolName: z.string(),\r\n toolCallId: z.string(),\r\n args: z.any().describe(\"Arguments passed to the tool\"),\r\n }),\r\n});\r\n\r\nexport const AgentToolResultSchema = EventCommonSchema.extend({\r\n type: z.literal(\"agent:tool:result\"),\r\n data: z.object({\r\n agentName: z.string(),\r\n toolName: z.string(),\r\n toolCallId: z.string(),\r\n output: z.any().optional().describe(\"Result returned by the tool\"),\r\n error: z.string().optional().describe(\"Error message if tool failed\"),\r\n durationMs: z.number().optional(),\r\n }),\r\n});\r\n\r\n// =============================================================================\r\n// Workflow Events\r\n// =============================================================================\r\n\r\nexport const WorkflowExecutionStartSchema = EventCommonSchema.extend({\r\n type: z.literal(\"workflow:execution:start\"),\r\n data: z.object({\r\n workflowId: z.string(),\r\n input: z.any().optional(),\r\n metadata: z.record(z.any()).optional(),\r\n }),\r\n});\r\n\r\nexport const WorkflowExecutionEndSchema = EventCommonSchema.extend({\r\n type: z.literal(\"workflow:execution:end\"),\r\n data: z.object({\r\n workflowId: z.string(),\r\n status: z.enum([\"success\", \"error\", \"truncated\"]),\r\n output: z.any().optional(),\r\n durationMs: z.number(),\r\n }),\r\n});\r\n\r\nexport const WorkflowExecutionErrorSchema = EventCommonSchema.extend({\r\n type: z.literal(\"workflow:execution:error\"),\r\n data: z.object({\r\n workflowId: z.string(),\r\n error: ErrorSchema,\r\n durationMs: z.number().optional(),\r\n }),\r\n});\r\n\r\nexport const WorkflowStepSchema = EventCommonSchema.extend({\r\n type: z.literal(\"workflow:step\"),\r\n data: z.object({\r\n workflowId: z.string(),\r\n stepName: z.string().optional(),\r\n nodeId: z.string().optional(),\r\n status: z.enum([\"running\", \"success\", \"error\"]),\r\n durationMs: z.number().optional(),\r\n output: z.any().optional(),\r\n error: ErrorSchema.optional(),\r\n }),\r\n});\r\n\r\n// =============================================================================\r\n// Discriminated Union\r\n// =============================================================================\r\n\r\nexport const NebulaEventSchema = z.discriminatedUnion(\"type\", [\r\n AgentExecutionStartSchema,\r\n AgentExecutionEndSchema,\r\n AgentExecutionErrorSchema,\r\n AgentLLMCallSchema,\r\n AgentLLMResponseSchema,\r\n AgentToolCallSchema,\r\n AgentToolResultSchema,\r\n WorkflowExecutionStartSchema,\r\n WorkflowExecutionEndSchema,\r\n WorkflowExecutionErrorSchema,\r\n WorkflowStepSchema,\r\n]);\r\n\r\n// =============================================================================\r\n// TypeScript Types\r\n// =============================================================================\r\n\r\nexport type TraceContext = z.infer<typeof TraceContextSchema>;\r\nexport type Usage = z.infer<typeof UsageSchema>;\r\nexport type NebulaEvent = z.infer<typeof NebulaEventSchema>;\r\n\r\n// Agent Types\r\nexport type AgentExecutionStart = z.infer<typeof AgentExecutionStartSchema>;\r\nexport type AgentExecutionEnd = z.infer<typeof AgentExecutionEndSchema>;\r\nexport type AgentExecutionError = z.infer<typeof AgentExecutionErrorSchema>;\r\nexport type AgentLLMCall = z.infer<typeof AgentLLMCallSchema>;\r\nexport type AgentLLMResponse = z.infer<typeof AgentLLMResponseSchema>;\r\nexport type AgentToolCall = z.infer<typeof AgentToolCallSchema>;\r\nexport type AgentToolResult = z.infer<typeof AgentToolResultSchema>;\r\n\r\n// Workflow Types\r\nexport type WorkflowExecutionStart = z.infer<typeof WorkflowExecutionStartSchema>;\r\nexport type WorkflowExecutionEnd = z.infer<typeof WorkflowExecutionEndSchema>;\r\nexport type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;\r\nexport type WorkflowStep = z.infer<typeof WorkflowStepSchema>;\r\n\r\n","export interface IPIIMasker {\r\n mask(text: string): string;\r\n}\r\n\r\nexport class RegexPIIMasker implements IPIIMasker {\r\n // Regex padrões para dados sensíveis brasileiros\r\n private static readonly PATTERNS = {\r\n CPF: /\\b\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}\\b/g,\r\n CNPJ: /\\b\\d{2}\\.?\\d{3}\\.?\\d{3}\\/?\\d{4}-?\\d{2}\\b/g,\r\n EMAIL: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b/g,\r\n PHONE: /\\b(\\(?\\d{2}\\)?\\s?)?(\\d{4,5}-?\\d{4})\\b/g,\r\n };\r\n\r\n mask(text: string): string {\r\n let masked = text;\r\n masked = masked.replace(RegexPIIMasker.PATTERNS.CPF, \"[CPF]\");\r\n masked = masked.replace(RegexPIIMasker.PATTERNS.CNPJ, \"[CNPJ]\");\r\n masked = masked.replace(RegexPIIMasker.PATTERNS.EMAIL, \"[EMAIL]\");\r\n masked = masked.replace(RegexPIIMasker.PATTERNS.PHONE, \"[PHONE]\");\r\n return masked;\r\n }\r\n}\r\n\r\n","export type EvaluationResult = {\r\n score: number; // 0 to 1\r\n passed: boolean;\r\n reason?: string;\r\n metadata?: Record<string, any>;\r\n};\r\n\r\nexport interface IScorer {\r\n name: string;\r\n evaluate(input: string, output: string, expected?: string): Promise<EvaluationResult>;\r\n}\r\n\r\n/**\r\n * Exemplo simples de Scorer: Valida se o output contém certas palavras-chave\r\n */\r\nexport class KeywordScorer implements IScorer {\r\n name = \"KeywordScorer\";\r\n\r\n constructor(private keywords: string[]) { }\r\n\r\n async evaluate(input: string, output: string): Promise<EvaluationResult> {\r\n const lowerOutput = output.toLowerCase();\r\n const found = this.keywords.filter(k => lowerOutput.includes(k.toLowerCase()));\r\n\r\n const score = found.length / this.keywords.length;\r\n\r\n return {\r\n score,\r\n passed: score === 1,\r\n reason: `Found ${found.length}/${this.keywords.length} keywords: ${found.join(\", \")}`,\r\n };\r\n }\r\n}\r\n\r\n","import { z } from \"zod\";\r\n\r\nexport type SchemaDefinition = Record<string, string | z.ZodTypeAny>;\r\n\r\nexport function schemaToZod(shape: SchemaDefinition) {\r\n const zodShape: any = {};\r\n \r\n for (const [key, value] of Object.entries(shape)) {\r\n if (typeof value === 'string') {\r\n let schema: z.ZodTypeAny = z.any();\r\n const isOptional = value.endsWith('?');\r\n const type = isOptional ? value.slice(0, -1) : value;\r\n\r\n switch (type) {\r\n case 'string': schema = z.string(); break;\r\n case 'number': schema = z.number(); break;\r\n case 'boolean': schema = z.boolean(); break;\r\n case 'array': schema = z.array(z.any()); break; // Simplificado\r\n default: schema = z.any();\r\n }\r\n\r\n if (isOptional) schema = schema.optional();\r\n zodShape[key] = schema;\r\n } else {\r\n zodShape[key] = value;\r\n }\r\n }\r\n return z.object(zodShape);\r\n}","import { z } from \"zod\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport type { IMemory } from \"../../agent/memory/index.js\";\r\nimport type { IModel } from \"../../agent/provider/index.js\";\r\n\r\n/**\r\n * Additional prompt used to steer coordination/selection/transfer,\r\n * not to rewrite the underlying agent instructions.\r\n */\r\nexport type AdditionalPrompt = string;\r\n\r\n/**\r\n * Memory configuration for delegation (AgentAsTool).\r\n */\r\nexport type DelegationMemoryConfig =\r\n | { type: \"shared\" }\r\n | { type: \"isolated\" }\r\n | { type: \"custom\"; memory: IMemory };\r\n\r\n/**\r\n * Edge definition for handoff graphs.\r\n */\r\nexport type HandoffEdge = {\r\n from: Agent;\r\n to: Agent;\r\n toolId: string;\r\n description?: string;\r\n};\r\n\r\n/**\r\n * RouterTeam configuration.\r\n */\r\nexport type RouterTeamConfig = {\r\n name: string;\r\n model: IModel;\r\n children: Agent[];\r\n fallback?: Agent;\r\n memory?: IMemory;\r\n additionalPrompt?: AdditionalPrompt;\r\n maxRetries?: number;\r\n timeoutMs?: number;\r\n};\r\n\r\n/**\r\n * HandoffTeam configuration.\r\n */\r\nexport type HandoffTeamConfig = {\r\n name: string;\r\n agents: Agent[];\r\n edges: HandoffEdge[];\r\n initialAgent: Agent;\r\n memory?: IMemory;\r\n additionalPrompt?: AdditionalPrompt;\r\n maxTransfers?: number;\r\n timeoutMs?: number;\r\n tokenBudget?: number;\r\n allowedTransitions?: Record<string, string[]>; // from -> list of allowed to (toolId optional at execution)\r\n onTransfer?: (from: Agent, to: Agent) => void | Promise<void>;\r\n};\r\n\r\n/**\r\n * AgentAsTool configuration.\r\n */\r\nexport type AgentAsToolConfig = {\r\n agent: Agent;\r\n id?: string;\r\n description?: string;\r\n additionalPrompt?: AdditionalPrompt;\r\n memory?: DelegationMemoryConfig;\r\n inputSchema?: z.ZodSchema;\r\n};\r\n\r\n/**\r\n * Aggregation strategies for committee-like behavior.\r\n */\r\nexport type AggregationStrategy = \"vote\" | \"summarize\" | \"confidence\" | \"first\";\r\n\r\n/**\r\n * HierarchicalTeam configuration.\r\n */\r\nexport type HierarchicalTeamConfig = {\r\n name: string;\r\n manager: Agent;\r\n workers: Agent[];\r\n memory?: IMemory;\r\n additionalPrompt?: AdditionalPrompt;\r\n allowHandoff?: boolean;\r\n workerCollaboration?: boolean;\r\n};\r\n\r\n/**\r\n * PipelineTeam configuration.\r\n */\r\nexport type PipelineTeamConfig = {\r\n name: string;\r\n stages: Agent[];\r\n memory?: IMemory;\r\n additionalPrompt?: AdditionalPrompt;\r\n};\r\n\r\n/**\r\n * CommitteeTeam configuration.\r\n */\r\nexport type CommitteeTeamConfig = {\r\n name: string;\r\n coordinator: Agent;\r\n members: Agent[];\r\n strategy: AggregationStrategy;\r\n memory?: IMemory;\r\n additionalPrompt?: AdditionalPrompt;\r\n parallel?: boolean;\r\n};\r\n\r\n// =============================================================================\r\n// Zod Schemas (runtime validation helpers)\r\n// =============================================================================\r\n\r\nconst agentRef = z.any(); // We avoid instanceof checks to prevent circular deps in runtime.\r\nconst memoryRef = z.any();\r\n\r\nexport const delegationMemorySchema = z.union([\r\n z.object({ type: z.literal(\"shared\") }),\r\n z.object({ type: z.literal(\"isolated\") }),\r\n z.object({\r\n type: z.literal(\"custom\"),\r\n memory: memoryRef,\r\n }),\r\n]);\r\n\r\nexport const handoffEdgeSchema = z.object({\r\n from: agentRef,\r\n to: agentRef,\r\n toolId: z.string(),\r\n description: z.string().optional(),\r\n});\r\n\r\nexport const routerTeamConfigSchema = z.object({\r\n model: z.any(),\r\n children: z.array(agentRef).min(1),\r\n fallback: agentRef.optional(),\r\n memory: memoryRef.optional(),\r\n additionalPrompt: z.string().optional(),\r\n maxRetries: z.number().int().positive().optional(),\r\n timeoutMs: z.number().int().positive().optional(),\r\n});\r\n\r\nexport const handoffTeamConfigSchema = z.object({\r\n agents: z.array(agentRef).min(1),\r\n edges: z.array(handoffEdgeSchema).min(1),\r\n initialAgent: agentRef,\r\n memory: memoryRef.optional(),\r\n additionalPrompt: z.string().optional(),\r\n maxTransfers: z.number().int().positive().optional(),\r\n timeoutMs: z.number().int().positive().optional(),\r\n tokenBudget: z.number().positive().optional(),\r\n allowedTransitions: z.record(z.array(z.string())).optional(),\r\n onTransfer: z.function().optional(),\r\n});\r\n\r\nexport const agentAsToolConfigSchema = z.object({\r\n agent: agentRef,\r\n id: z.string().optional(),\r\n description: z.string().optional(),\r\n additionalPrompt: z.string().optional(),\r\n memory: delegationMemorySchema.optional(),\r\n inputSchema: z.custom<z.ZodSchema>().optional(),\r\n});\r\n\r\nexport const hierarchicalTeamConfigSchema = z.object({\r\n manager: agentRef,\r\n workers: z.array(agentRef).min(1),\r\n memory: memoryRef.optional(),\r\n additionalPrompt: z.string().optional(),\r\n allowHandoff: z.boolean().optional(),\r\n workerCollaboration: z.boolean().optional(),\r\n});\r\n\r\nexport const pipelineTeamConfigSchema = z.object({\r\n stages: z.array(agentRef).min(1),\r\n memory: memoryRef.optional(),\r\n additionalPrompt: z.string().optional(),\r\n});\r\n\r\nexport const committeeTeamConfigSchema = z.object({\r\n coordinator: agentRef,\r\n members: z.array(agentRef).min(1),\r\n strategy: z.enum([\"vote\", \"summarize\", \"confidence\", \"first\"]),\r\n memory: memoryRef.optional(),\r\n additionalPrompt: z.string().optional(),\r\n parallel: z.boolean().optional(),\r\n});\r\n\r\nexport const aggregationStrategySchema = z.enum([\r\n \"vote\",\r\n \"summarize\",\r\n \"confidence\",\r\n \"first\",\r\n]);\r\n\r\nexport type {\r\n AgentAsToolConfig as AgentAsToolConfigType,\r\n RouterTeamConfig as RouterTeamConfigType,\r\n HandoffTeamConfig as HandoffTeamConfigType,\r\n HierarchicalTeamConfig as HierarchicalTeamConfigType,\r\n PipelineTeamConfig as PipelineTeamConfigType,\r\n CommitteeTeamConfig as CommitteeTeamConfigType,\r\n};\r\n\r\n\r\n","import { InMemory } from \"../../agent/memory/in-memory.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport type { IMemory } from \"../../agent/memory/index.js\";\r\nimport type { DelegationMemoryConfig } from \"../types/index.js\";\r\n\r\nexport function overrideAgentMemory(agent: Agent, memory?: IMemory) {\r\n const original = agent.config.memory;\r\n if (memory) {\r\n agent.config.memory = memory;\r\n }\r\n return () => {\r\n agent.config.memory = original;\r\n };\r\n}\r\n\r\nexport async function resolveDelegationMemory(\r\n agent: Agent,\r\n config?: DelegationMemoryConfig,\r\n callingMemory?: IMemory\r\n): Promise<{ memory: IMemory; restore: () => void }> {\r\n const original = agent.config.memory;\r\n\r\n if (!config) {\r\n return { memory: original, restore: () => {} };\r\n }\r\n\r\n if (config.type === \"shared\") {\r\n // Share calling history into the target's memory, without replacing it.\r\n const memory = original;\r\n if (callingMemory) {\r\n const msgs = await callingMemory.getMessages();\r\n for (const msg of msgs) {\r\n await memory.addMessage(msg);\r\n }\r\n }\r\n agent.config.memory = memory;\r\n return { memory, restore: () => (agent.config.memory = original) };\r\n }\r\n\r\n if (config.type === \"custom\") {\r\n agent.config.memory = config.memory;\r\n return { memory: config.memory, restore: () => (agent.config.memory = original) };\r\n }\r\n\r\n // isolated\r\n const isolated = new InMemory();\r\n agent.config.memory = isolated;\r\n return { memory: isolated, restore: () => (agent.config.memory = original) };\r\n}\r\n\r\n\r\n","import type { Agent } from \"../../agent/Agent.js\";\r\nimport type { IMemory } from \"../../agent/memory/index.js\";\r\nimport { Tool } from \"../../agent/tools/index.js\";\r\nimport type { AgentResult } from \"../../agent/Agent.js\";\r\nimport { resolveDelegationMemory } from \"../utils/memory.js\";\r\nimport type { AgentAsToolConfig, DelegationMemoryConfig } from \"../types/index.js\";\r\n\r\ntype ToolInput = any;\r\n\r\nexport class AgentAsTool extends Tool {\r\n private callingMemory?: IMemory;\r\n private readonly target: Agent;\r\n private readonly memoryConfig?: DelegationMemoryConfig;\r\n private readonly extraPrompt?: string;\r\n\r\n constructor(config: AgentAsToolConfig) {\r\n const toolId =\r\n config.id ??\r\n `delegate_${config.agent.name.toLowerCase().replace(/\\s+/g, \"_\")}`;\r\n const description =\r\n config.description ??\r\n `Delegate to specialist agent: ${config.agent.name}`;\r\n\r\n super({\r\n id: toolId,\r\n description,\r\n inputSchema: config.inputSchema,\r\n handler: async (_, input: ToolInput) => {\r\n return this.runDelegated(input);\r\n },\r\n });\r\n\r\n this.target = config.agent;\r\n this.memoryConfig = config.memory;\r\n this.extraPrompt = config.additionalPrompt;\r\n }\r\n\r\n /**\r\n * Allows orchestrators to set the calling agent/team memory when using\r\n * `memory: { type: \"shared\" }`.\r\n */\r\n public setCallingMemory(memory?: IMemory) {\r\n this.callingMemory = memory;\r\n }\r\n\r\n private async runDelegated(input: ToolInput): Promise<AgentResult[\"content\"]> {\r\n const { restore } = await resolveDelegationMemory(\r\n this.target,\r\n this.memoryConfig,\r\n this.callingMemory\r\n );\r\n\r\n try {\r\n const formattedInput =\r\n typeof input === \"string\" ? input : JSON.stringify(input);\r\n\r\n const userContent = this.extraPrompt\r\n ? `${this.extraPrompt}\\nInput: ${formattedInput}`\r\n : formattedInput;\r\n\r\n await this.target.config.memory.addMessage({\r\n role: \"user\",\r\n content: userContent,\r\n });\r\n\r\n const result = await this.target.execute();\r\n return result.content;\r\n } finally {\r\n restore();\r\n }\r\n }\r\n}\r\n\r\n\r\n","import type { Agent } from \"../../agent/Agent.js\";\r\nimport type { AdditionalPrompt } from \"../types/index.js\";\r\n\r\nexport function buildRouterSystemPrompt(\r\n agents: Agent[],\r\n additionalPrompt?: AdditionalPrompt\r\n) {\r\n const lines = agents.map(\r\n (a) => `- ${a.name}: ${a.config?.instructions ?? a.name}`\r\n );\r\n\r\n return [\r\n \"You are a routing controller.\",\r\n \"Choose the best agent for the user request.\",\r\n \"Respond ONLY with JSON: {\\\"agent\\\": \\\"<name>\\\"}.\",\r\n additionalPrompt ? `Guidance: ${additionalPrompt}` : \"\",\r\n \"Available agents:\",\r\n ...lines,\r\n ]\r\n .filter(Boolean)\r\n .join(\"\\n\");\r\n}\r\n\r\nexport function buildHandoffSystemPrompt(additionalPrompt?: AdditionalPrompt) {\r\n return [\r\n \"You are coordinating handoffs between agents.\",\r\n additionalPrompt ? `Guidance: ${additionalPrompt}` : \"\",\r\n ]\r\n .filter(Boolean)\r\n .join(\"\\n\");\r\n}\r\n\r\n\r\n","export class GuardrailError extends Error {\r\n constructor(message: string) {\r\n super(message);\r\n this.name = \"GuardrailError\";\r\n }\r\n}\r\n\r\nexport function enforceMaxTransfers(current: number, max?: number) {\r\n if (max !== undefined && current >= max) {\r\n throw new GuardrailError(`Max transfers exceeded (${max})`);\r\n }\r\n}\r\n\r\nexport function enforceAllowedTransition(\r\n from: string,\r\n to: string,\r\n allowed?: Record<string, string[]>\r\n) {\r\n if (!allowed) return;\r\n const allowedTargets = allowed[from];\r\n if (allowedTargets && !allowedTargets.includes(to)) {\r\n throw new GuardrailError(`Transition from '${from}' to '${to}' is not allowed`);\r\n }\r\n}\r\n\r\nexport function enforceTimeout<T>(\r\n promise: Promise<T>,\r\n timeoutMs?: number,\r\n label = \"operation\"\r\n): Promise<T> {\r\n if (!timeoutMs) return promise;\r\n return Promise.race([\r\n promise,\r\n new Promise<T>((_, reject) =>\r\n setTimeout(() => reject(new GuardrailError(`${label} timed out after ${timeoutMs}ms`)), timeoutMs)\r\n ),\r\n ]);\r\n}\r\n\r\n\r\n","import type { AgentResult } from \"../../agent/Agent.js\";\r\nimport type { Message } from \"../../agent/provider/index.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport { BaseAgent } from \"../../agent/BaseAgent.js\";\r\nimport type { AgentExecuteOptions } from \"../../agent/Agent.js\";\r\nimport { buildRouterSystemPrompt } from \"../utils/prompts.js\";\r\nimport { overrideAgentMemory } from \"../utils/memory.js\";\r\nimport { enforceTimeout } from \"../utils/guardrails.js\";\r\nimport type { RouterTeamConfig } from \"../types/index.js\";\r\nimport { Tracing } from \"../../tracing/index.js\";\r\n\r\nexport class RouterTeam extends BaseAgent {\r\n constructor(private readonly config: RouterTeamConfig) {\r\n super(\r\n config.name,\r\n undefined,\r\n config.memory ?? config.children?.[0]?.config?.memory\r\n );\r\n }\r\n\r\n /**\r\n * Execute routing: choose an agent via model classification, then delegate execution.\r\n */\r\n async execute(input?: string, _options?: AgentExecuteOptions): Promise<AgentResult> {\r\n const correlationId = `router_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n const startTime = Date.now();\r\n\r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `team:router:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (teamSpan) => {\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: input,\r\n },\r\n });\r\n\r\n try {\r\n const selected = await this.selectAgent(input);\r\n const memoryToUse = this.config.memory ?? selected.config.memory;\r\n const restoreMemory = overrideAgentMemory(selected, memoryToUse);\r\n\r\n if (input) {\r\n await this.addMessage({ role: \"user\", content: input });\r\n }\r\n\r\n const result = await selected.execute();\r\n restoreMemory();\r\n\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: result.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n durationMs: Date.now() - startTime,\r\n // Usage? Ideally aggregated, but for now passing result content is key\r\n },\r\n });\r\n\r\n await teamSpan.end({\r\n status: result.truncated ? \"cancelled\" : \"success\",\r\n data: { output: result.content },\r\n });\r\n return result;\r\n } catch (error: any) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private async selectAgent(userInput?: string): Promise<Agent> {\r\n const system = buildRouterSystemPrompt(\r\n this.config.children,\r\n this.config.additionalPrompt\r\n );\r\n\r\n const messages: Message[] = [\r\n { role: \"system\", content: system },\r\n { role: \"user\", content: userInput ?? \"\" },\r\n ];\r\n\r\n const routerResponseSchema = {\r\n type: \"object\",\r\n properties: {\r\n agent: {\r\n type: \"string\",\r\n description: \"The name of the agent to route to\",\r\n },\r\n },\r\n required: [\"agent\"],\r\n additionalProperties: false,\r\n };\r\n\r\n const response = await enforceTimeout(\r\n Tracing.withSpan(\r\n {\r\n kind: \"llm\",\r\n name: \"llm:router-selection\",\r\n data: {\r\n provider: this.config.model.providerName,\r\n model: this.config.model.modelName,\r\n messagesCount: messages.length,\r\n toolsCount: 0,\r\n responseFormat: { type: \"json\", schema: routerResponseSchema },\r\n },\r\n },\r\n async (llmSpan) => {\r\n const resp = await this.config.model.generate(messages, undefined, {\r\n responseFormat: { type: \"json\", schema: routerResponseSchema },\r\n });\r\n await llmSpan.end({\r\n status: \"success\",\r\n data: {\r\n usage: resp.usage,\r\n outputPreview: typeof resp.content === \"string\" ? resp.content.substring(0, 200) : \"json_content\",\r\n },\r\n });\r\n return resp;\r\n }\r\n ),\r\n this.config.timeoutMs,\r\n \"router-selection\"\r\n );\r\n\r\n const agentName = this.extractAgentName(response.content);\r\n const found =\r\n this.config.children.find(\r\n (c) => c.name.toLowerCase() === agentName?.toLowerCase()\r\n ) ??\r\n this.config.fallback ??\r\n this.config.children[0];\r\n\r\n return found;\r\n }\r\n\r\n private extractAgentName(content: string | null): string | undefined {\r\n if (!content) return undefined;\r\n const trimmed = content.trim();\r\n if (!trimmed) return undefined;\r\n\r\n try {\r\n const parsed = JSON.parse(trimmed);\r\n if (parsed && typeof parsed.agent === \"string\") {\r\n return parsed.agent;\r\n }\r\n } catch {\r\n // ignore\r\n }\r\n\r\n return trimmed.split(\"\\n\")[0];\r\n }\r\n}\r\n","import type { AgentResult } from \"../../agent/Agent.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport { BaseAgent } from \"../../agent/BaseAgent.js\";\r\nimport type { AgentExecuteOptions } from \"../../agent/Agent.js\";\r\nimport { Tool } from \"../../agent/tools/index.js\";\r\nimport {\r\n enforceAllowedTransition,\r\n enforceMaxTransfers,\r\n enforceTimeout,\r\n} from \"../utils/guardrails.js\";\r\nimport { overrideAgentMemory } from \"../utils/memory.js\";\r\nimport type { HandoffEdge, HandoffTeamConfig } from \"../types/index.js\";\r\nimport { Tracing } from \"../../tracing/index.js\";\r\n\r\ntype HandoffSignal = { handoff: true; to: string };\r\n\r\nexport class HandoffTeam extends BaseAgent {\r\n private readonly edgeMap: Map<Agent, HandoffEdge[]>;\r\n private readonly agentByName: Map<string, Agent>;\r\n\r\n constructor(private readonly config: HandoffTeamConfig) {\r\n super(config.name, undefined, config.memory ?? config.initialAgent.config.memory);\r\n this.edgeMap = this.buildEdgeMap(config.edges);\r\n this.agentByName = new Map(\r\n config.agents.map((a) => [a.name.toLowerCase(), a])\r\n );\r\n }\r\n\r\n async execute(input?: string, _options?: AgentExecuteOptions): Promise<AgentResult> {\r\n const correlationId = `handoff_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n const startTime = Date.now();\r\n\r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `team:handoff:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (teamSpan) => {\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: input,\r\n },\r\n });\r\n\r\n try {\r\n const teamMemory = this.config.memory ?? this.config.initialAgent.config.memory;\r\n let current = this.config.initialAgent;\r\n let transfers = 0;\r\n\r\n if (input) {\r\n await this.addMessage({ role: \"user\", content: input });\r\n }\r\n\r\n let lastResult: AgentResult | undefined;\r\n\r\n while (true) {\r\n enforceMaxTransfers(transfers, this.config.maxTransfers);\r\n\r\n const { tools, restoreTools } = this.attachHandoffTools(current);\r\n const restoreMemory = overrideAgentMemory(current, teamMemory);\r\n\r\n try {\r\n const result = await enforceTimeout(\r\n current.execute(),\r\n this.config.timeoutMs,\r\n \"handoff-execution\"\r\n );\r\n \r\n lastResult = result;\r\n\r\n const handoff = this.findHandoffSignal(result, tools);\r\n if (!handoff) {\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: result.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({\r\n status: result.truncated ? \"cancelled\" : \"success\",\r\n data: { output: result.content },\r\n });\r\n return result;\r\n }\r\n\r\n transfers++;\r\n enforceAllowedTransition(\r\n current.name,\r\n handoff.to,\r\n this.config.allowedTransitions\r\n );\r\n\r\n if (this.config.onTransfer) {\r\n const target = this.agentByName.get(handoff.to.toLowerCase());\r\n if (target) {\r\n await this.config.onTransfer(current, target);\r\n }\r\n }\r\n\r\n const next = this.agentByName.get(handoff.to.toLowerCase());\r\n if (!next) {\r\n throw new Error(`Handoff target not found: ${handoff.to}`);\r\n }\r\n current = next;\r\n continue;\r\n } finally {\r\n restoreTools();\r\n restoreMemory();\r\n }\r\n }\r\n } catch (error: any) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private buildEdgeMap(edges: HandoffEdge[]): Map<Agent, HandoffEdge[]> {\r\n const map = new Map<Agent, HandoffEdge[]>();\r\n edges.forEach((edge) => {\r\n const list = map.get(edge.from) ?? [];\r\n list.push(edge);\r\n map.set(edge.from, list);\r\n });\r\n return map;\r\n }\r\n\r\n private attachHandoffTools(agent: Agent): { tools: Tool[]; restoreTools: () => void } {\r\n const edges = this.edgeMap.get(agent) ?? [];\r\n const newTools = edges.map(\r\n (edge) =>\r\n new Tool({\r\n id: edge.toolId,\r\n description:\r\n edge.description ??\r\n `Transfer control to ${edge.to.name} (${edge.to.config.instructions})`,\r\n handler: async (): Promise<HandoffSignal> => ({\r\n handoff: true,\r\n to: edge.to.name,\r\n }),\r\n })\r\n );\r\n\r\n const originalTools = agent.config.tools ?? [];\r\n agent.config.tools = [...originalTools, ...newTools];\r\n\r\n return {\r\n tools: newTools,\r\n restoreTools: () => {\r\n agent.config.tools = originalTools;\r\n },\r\n };\r\n }\r\n\r\n private findHandoffSignal(\r\n result: AgentResult,\r\n tools: Tool[]\r\n ): HandoffSignal | undefined {\r\n if (!result.toolExecutions?.length) return undefined;\r\n const toolIds = new Set(tools.map((t) => t.id));\r\n\r\n for (const exec of result.toolExecutions) {\r\n if (toolIds.has(exec.name) && exec.output && (exec.output as HandoffSignal).handoff) {\r\n return exec.output as HandoffSignal;\r\n }\r\n }\r\n return undefined;\r\n }\r\n}\r\n","import type { AgentResult } from \"../../agent/Agent.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport { BaseAgent } from \"../../agent/BaseAgent.js\";\r\nimport type { AgentExecuteOptions } from \"../../agent/Agent.js\";\r\nimport { AgentAsTool } from \"../agent-as-tool/AgentAsTool.js\";\r\nimport { HandoffTeam } from \"../handoff-team/HandoffTeam.js\";\r\nimport { overrideAgentMemory } from \"../utils/memory.js\";\r\nimport type { HierarchicalTeamConfig } from \"../types/index.js\";\r\nimport { Tracing } from \"../../tracing/index.js\";\r\n\r\nexport class HierarchicalTeam extends BaseAgent {\r\n private readonly manager: Agent;\r\n private readonly workers: Agent[];\r\n private readonly teamMemory?: Agent[\"config\"][\"memory\"];\r\n private readonly allowHandoff: boolean;\r\n private readonly workerCollaboration: boolean;\r\n\r\n constructor(private readonly config: HierarchicalTeamConfig) {\r\n super(config.name, undefined, config.memory ?? config.manager.config.memory);\r\n this.manager = config.manager;\r\n this.workers = config.workers;\r\n this.teamMemory = config.memory;\r\n this.allowHandoff = config.allowHandoff ?? false;\r\n this.workerCollaboration = config.workerCollaboration ?? false;\r\n }\r\n\r\n async execute(input?: string, _options?: AgentExecuteOptions): Promise<AgentResult> {\r\n const correlationId = `hierarchical_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n const startTime = Date.now();\r\n \r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `team:hierarchical:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (teamSpan) => {\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: input,\r\n },\r\n });\r\n\r\n try {\r\n const result = this.allowHandoff\r\n ? await this.executeWithHandoff(input)\r\n : await this.executeDelegationOnly(input);\r\n\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: result.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n\r\n await teamSpan.end({\r\n status: result.truncated ? \"cancelled\" : \"success\",\r\n data: { output: result.content },\r\n });\r\n return result;\r\n } catch (error: any) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private async executeDelegationOnly(input?: string): Promise<AgentResult> {\r\n const teamMemory = this.teamMemory ?? this.manager.config.memory;\r\n const tools = this.buildWorkerTools(teamMemory);\r\n\r\n const originalTools = this.manager.config.tools ?? [];\r\n this.manager.config.tools = [...originalTools, ...tools];\r\n const restoreMemory = overrideAgentMemory(this.manager, teamMemory);\r\n\r\n try {\r\n if (input) {\r\n await this.addMessage({ role: \"user\", content: input });\r\n }\r\n return await this.manager.execute();\r\n } finally {\r\n this.manager.config.tools = originalTools;\r\n restoreMemory();\r\n tools.forEach((t) => t.setCallingMemory(undefined));\r\n }\r\n }\r\n\r\n private async executeWithHandoff(input?: string): Promise<AgentResult> {\r\n const teamMemory = this.teamMemory ?? this.manager.config.memory;\r\n\r\n if (this.workerCollaboration) {\r\n this.workers.forEach((worker) => {\r\n const originalTools = worker.config.tools ?? [];\r\n const peerTools = this.workers\r\n .filter((w) => w !== worker)\r\n .map(\r\n (w) =>\r\n new AgentAsTool({\r\n agent: w,\r\n memory: { type: \"shared\" },\r\n additionalPrompt: \"Use this to consult another specialist.\",\r\n })\r\n );\r\n worker.config.tools = [...originalTools, ...peerTools];\r\n });\r\n }\r\n\r\n const team = new HandoffTeam({\r\n name: `${this.config.name}-internal-handoff`,\r\n agents: [this.manager, ...this.workers],\r\n edges: [\r\n ...this.workers.map((w) => ({\r\n from: this.manager,\r\n to: w,\r\n toolId: `handoff_to_${w.name.toLowerCase()}`,\r\n description: `Pass control to worker ${w.name}`,\r\n })),\r\n ...this.workers.map((w) => ({\r\n from: w,\r\n to: this.manager,\r\n toolId: `back_to_manager`,\r\n description: `Return control to manager`,\r\n })),\r\n ],\r\n initialAgent: this.manager,\r\n memory: teamMemory,\r\n additionalPrompt: this.config.additionalPrompt,\r\n maxTransfers: 10,\r\n });\r\n\r\n return team.execute(input);\r\n }\r\n\r\n private buildWorkerTools(teamMemory: Agent[\"config\"][\"memory\"]) {\r\n return this.workers.map((worker) => {\r\n const tool = new AgentAsTool({\r\n agent: worker,\r\n id: `delegate_${worker.name.toLowerCase()}`,\r\n memory: { type: \"shared\" },\r\n additionalPrompt: \"Delegate a subtask to this specialist.\",\r\n });\r\n tool.setCallingMemory(teamMemory);\r\n return tool;\r\n });\r\n }\r\n}\r\n","import type { AgentResult } from \"../../agent/Agent.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport { BaseAgent } from \"../../agent/BaseAgent.js\";\r\nimport type { AgentExecuteOptions } from \"../../agent/Agent.js\";\r\nimport { HandoffTeam } from \"../handoff-team/HandoffTeam.js\";\r\nimport type { PipelineTeamConfig } from \"../types/index.js\";\r\nimport { Tracing } from \"../../tracing/index.js\";\r\n\r\nexport class PipelineTeam extends BaseAgent {\r\n private readonly stages: Agent[];\r\n private readonly teamMemory?: Agent[\"config\"][\"memory\"];\r\n\r\n constructor(private readonly config: PipelineTeamConfig) {\r\n super(config.name, undefined, config.memory ?? config.stages?.[0]?.config?.memory);\r\n this.stages = config.stages;\r\n this.teamMemory = config.memory;\r\n }\r\n\r\n async execute(input?: string, _options?: AgentExecuteOptions): Promise<AgentResult> {\r\n const correlationId = `pipeline_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n const startTime = Date.now();\r\n\r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `team:pipeline:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (teamSpan) => {\r\n \r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: input,\r\n },\r\n });\r\n\r\n try {\r\n const edges = this.buildEdges();\r\n const team = new HandoffTeam({\r\n name: `${this.config.name}-internal-handoff`,\r\n agents: this.stages,\r\n edges,\r\n initialAgent: this.stages[0],\r\n memory: this.teamMemory,\r\n additionalPrompt: this.config.additionalPrompt,\r\n maxTransfers: edges.length + 2,\r\n });\r\n\r\n const result = await team.execute(input);\r\n\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: result.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n\r\n await teamSpan.end({\r\n status: result.truncated ? \"cancelled\" : \"success\",\r\n data: { output: result.content },\r\n });\r\n return result;\r\n } catch (error: any) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private buildEdges() {\r\n const edges = this.stages.slice(0, -1).map((from, idx) => {\r\n const to = this.stages[idx + 1];\r\n return {\r\n from,\r\n to,\r\n toolId: `next_${to.name.toLowerCase()}`,\r\n description: `Pass work to ${to.name}`,\r\n };\r\n });\r\n\r\n return edges;\r\n }\r\n}\r\n","import type { AgentResult } from \"../../agent/Agent.js\";\r\nimport type { Agent } from \"../../agent/Agent.js\";\r\nimport { BaseAgent } from \"../../agent/BaseAgent.js\";\r\nimport type { AgentExecuteOptions } from \"../../agent/Agent.js\";\r\nimport { overrideAgentMemory } from \"../utils/memory.js\";\r\nimport type { CommitteeTeamConfig } from \"../types/index.js\";\r\nimport { Tracing } from \"../../tracing/index.js\";\r\n\r\ntype MemberOpinion = { agent: string; content: any };\r\n\r\nexport class CommitteeTeam extends BaseAgent {\r\n private readonly coordinator: Agent;\r\n private readonly members: Agent[];\r\n private readonly strategy: CommitteeTeamConfig[\"strategy\"];\r\n private readonly teamMemory?: Agent[\"config\"][\"memory\"];\r\n\r\n constructor(private readonly config: CommitteeTeamConfig) {\r\n super(config.name, undefined, config.memory ?? config.coordinator.config.memory);\r\n this.coordinator = config.coordinator;\r\n this.members = config.members;\r\n this.strategy = config.strategy;\r\n this.teamMemory = config.memory;\r\n }\r\n\r\n async execute(input?: string, _options?: AgentExecuteOptions): Promise<AgentResult> {\r\n const correlationId = `committee_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\r\n const startTime = Date.now();\r\n\r\n return Tracing.withSpan(\r\n {\r\n kind: \"agent\",\r\n name: `team:committee:${this.name}`,\r\n correlationId,\r\n data: { agentName: this.name, input },\r\n },\r\n async (teamSpan) => {\r\n this.emit(\"agent:execution:start\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n input: input,\r\n },\r\n });\r\n\r\n try {\r\n const teamMemory = this.teamMemory ?? this.coordinator.config.memory;\r\n const opinions = await this.collectOpinions(teamMemory, input);\r\n const aggregated = this.aggregate(opinions);\r\n\r\n const restoreMemory = overrideAgentMemory(this.coordinator, teamMemory);\r\n let result: AgentResult;\r\n try {\r\n await this.addMessage({\r\n role: \"user\",\r\n content: `Members opinions:\\n${opinions\r\n .map((o) => `- ${o.agent}: ${o.content}`)\r\n .join(\"\\n\")}\\nStrategy: ${this.strategy}`,\r\n });\r\n\r\n if (input) {\r\n await this.addMessage({ role: \"user\", content: input });\r\n }\r\n\r\n const coordinatorResult = await this.coordinator.execute();\r\n result = coordinatorResult ?? this.buildResult(aggregated);\r\n } finally {\r\n restoreMemory();\r\n }\r\n\r\n this.emit(\"agent:execution:end\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n status: result.truncated ? \"truncated\" : \"success\",\r\n output: result.content,\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n\r\n await teamSpan.end({\r\n status: result.truncated ? \"cancelled\" : \"success\",\r\n data: { output: result.content },\r\n });\r\n return result;\r\n } catch (error: any) {\r\n const err = error instanceof Error ? error : new Error(String(error));\r\n this.emit(\"agent:execution:error\", {\r\n correlationId,\r\n data: {\r\n agentName: this.name,\r\n error: {\r\n message: err.message,\r\n stack: err.stack,\r\n name: err.name,\r\n },\r\n durationMs: Date.now() - startTime,\r\n },\r\n });\r\n await teamSpan.end({ status: \"error\" });\r\n throw error;\r\n }\r\n }\r\n );\r\n }\r\n\r\n private async collectOpinions(memory: Agent[\"config\"][\"memory\"], input?: string) {\r\n const opinions: MemberOpinion[] = [];\r\n\r\n for (const member of this.members) {\r\n const restoreMemory = overrideAgentMemory(member, memory);\r\n try {\r\n if (input) {\r\n await memory.addMessage({ role: \"user\", content: input });\r\n }\r\n const result = await member.execute();\r\n opinions.push({ agent: member.name, content: result.content });\r\n } finally {\r\n restoreMemory();\r\n }\r\n }\r\n\r\n return opinions;\r\n }\r\n\r\n private aggregate(opinions: MemberOpinion[]) {\r\n if (this.strategy === \"first\") {\r\n return opinions[0]?.content;\r\n }\r\n\r\n if (this.strategy === \"vote\") {\r\n const counts = opinions.reduce<Record<string, number>>((acc, o) => {\r\n const key = String(o.content);\r\n acc[key] = (acc[key] || 0) + 1;\r\n return acc;\r\n }, {});\r\n return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0];\r\n }\r\n\r\n if (this.strategy === \"confidence\") {\r\n return opinions[0]?.content;\r\n }\r\n\r\n return opinions.map((o) => `${o.agent}: ${o.content}`).join(\" | \");\r\n }\r\n\r\n private buildResult(content: any): AgentResult {\r\n return {\r\n content,\r\n toolExecutions: [],\r\n llmCalls: 0,\r\n totalDurationMs: 0,\r\n truncated: false,\r\n };\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA6B;;;ACA7B,8BAAkC;AAClC,yBAA2B;AA2BpB,IAAM,aAAN,MAAkE;AAAA,EAGvE,YACkB,SACA,QACA,cACA,MACA,MACC,eACA,OACA,UACjB;AARgB;AACA;AACA;AACA;AACA;AACC;AACA;AACA;AAAA,EAChB;AAAA,EAXK,QAAQ;AAAA,EAahB,MAAM,IAAI,OAAuC;AAC/C,QAAI,KAAK,MAAO;AAChB,SAAK,QAAQ;AAEb,UAAM,QAA0B;AAAA,MAC9B,GAA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