@opperai/agents 0.1.0 → 0.1.3

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/dist/index.d.cts CHANGED
@@ -592,6 +592,38 @@ declare class HookManager {
592
592
  }
593
593
  declare const createHookManager: (logger?: AgentLogger) => HookManager;
594
594
 
595
+ /**
596
+ * Options for generating agent flow visualization
597
+ */
598
+ interface VisualizationOptions {
599
+ /**
600
+ * Optional file path to save the Mermaid diagram
601
+ * If provided, the diagram will be saved to this path
602
+ * .md extension will be added automatically if not present
603
+ */
604
+ outputPath?: string;
605
+ /**
606
+ * Whether to include MCP tool providers in the visualization
607
+ * When true, will show expanded tools from providers
608
+ * When false, will show providers as single nodes
609
+ * @default false
610
+ */
611
+ includeMcpTools?: boolean;
612
+ /**
613
+ * Internal parameter to track visited agents (prevents cycles)
614
+ * @internal
615
+ */
616
+ _visited?: Set<string>;
617
+ }
618
+ /**
619
+ * Generate Mermaid graph diagram for an agent's structure and flow
620
+ *
621
+ * @param agent - The agent to visualize
622
+ * @param options - Visualization options
623
+ * @returns Mermaid markdown string, or file path if outputPath was provided
624
+ */
625
+ declare function generateAgentFlowDiagram<I, O>(agent: BaseAgent<I, O>, options?: VisualizationOptions): Promise<string>;
626
+
595
627
  /**
596
628
  * Schema for memory entry metadata
597
629
  */
@@ -635,8 +667,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
635
667
  updatedAt: number;
636
668
  accessCount: number;
637
669
  };
638
- key: string;
639
670
  description: string;
671
+ key: string;
640
672
  value?: unknown;
641
673
  }, {
642
674
  metadata: {
@@ -644,8 +676,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
644
676
  updatedAt: number;
645
677
  accessCount?: number | undefined;
646
678
  };
647
- key: string;
648
679
  description: string;
680
+ key: string;
649
681
  value?: unknown;
650
682
  }>;
651
683
  type MemoryEntry = z.infer<typeof MemoryEntrySchema>;
@@ -1014,6 +1046,28 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
1014
1046
  private registerTools;
1015
1047
  private activateToolProviders;
1016
1048
  private deactivateToolProviders;
1049
+ /**
1050
+ * Generate a Mermaid flowchart diagram visualizing the agent's structure and flow.
1051
+ * Shows tools, hooks, schemas, providers, and nested agents.
1052
+ *
1053
+ * @param options - Visualization options
1054
+ * @returns Mermaid markdown string, or file path if outputPath was provided
1055
+ *
1056
+ * @example
1057
+ * ```typescript
1058
+ * // Generate diagram string
1059
+ * const diagram = await agent.visualizeFlow();
1060
+ * console.log(diagram);
1061
+ *
1062
+ * // Save to file
1063
+ * const path = await agent.visualizeFlow({ outputPath: "agent_flow.md" });
1064
+ * console.log(`Saved to ${path}`);
1065
+ *
1066
+ * // Include MCP tools details
1067
+ * const diagram = await agent.visualizeFlow({ includeMcpTools: true });
1068
+ * ```
1069
+ */
1070
+ visualizeFlow(options?: VisualizationOptions): Promise<string>;
1017
1071
  }
1018
1072
 
1019
1073
  /**
@@ -1491,9 +1545,9 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1491
1545
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1492
1546
  }, "strip", z.ZodTypeAny, {
1493
1547
  metadata: Record<string, unknown>;
1548
+ name: string;
1494
1549
  method: "GET" | "POST";
1495
1550
  headers: Record<string, string>;
1496
- name: string;
1497
1551
  timeout: number;
1498
1552
  transport: "http-sse";
1499
1553
  url: string;
@@ -1516,8 +1570,8 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1516
1570
  sessionId: z.ZodOptional<z.ZodString>;
1517
1571
  }, "strip", z.ZodTypeAny, {
1518
1572
  metadata: Record<string, unknown>;
1519
- headers: Record<string, string>;
1520
1573
  name: string;
1574
+ headers: Record<string, string>;
1521
1575
  timeout: number;
1522
1576
  transport: "streamable-http";
1523
1577
  url: string;
@@ -1575,9 +1629,9 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1575
1629
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1576
1630
  }, "strip", z.ZodTypeAny, {
1577
1631
  metadata: Record<string, unknown>;
1632
+ name: string;
1578
1633
  method: "GET" | "POST";
1579
1634
  headers: Record<string, string>;
1580
- name: string;
1581
1635
  timeout: number;
1582
1636
  transport: "http-sse";
1583
1637
  url: string;
@@ -1600,8 +1654,8 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1600
1654
  sessionId: z.ZodOptional<z.ZodString>;
1601
1655
  }, "strip", z.ZodTypeAny, {
1602
1656
  metadata: Record<string, unknown>;
1603
- headers: Record<string, string>;
1604
1657
  name: string;
1658
+ headers: Record<string, string>;
1605
1659
  timeout: number;
1606
1660
  transport: "streamable-http";
1607
1661
  url: string;
@@ -1626,16 +1680,16 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1626
1680
  stderr?: "inherit" | "pipe" | "ignore" | undefined;
1627
1681
  } | {
1628
1682
  metadata: Record<string, unknown>;
1683
+ name: string;
1629
1684
  method: "GET" | "POST";
1630
1685
  headers: Record<string, string>;
1631
- name: string;
1632
1686
  timeout: number;
1633
1687
  transport: "http-sse";
1634
1688
  url: string;
1635
1689
  } | {
1636
1690
  metadata: Record<string, unknown>;
1637
- headers: Record<string, string>;
1638
1691
  name: string;
1692
+ headers: Record<string, string>;
1639
1693
  timeout: number;
1640
1694
  transport: "streamable-http";
1641
1695
  url: string;
@@ -1924,4 +1978,4 @@ declare class ToolRunner {
1924
1978
  };
1925
1979
  }
1926
1980
 
1927
- export { Agent, type AgentConfig, AgentContext, type AgentContextOptions, type AgentContextSnapshot, type AgentDecision, AgentDecisionSchema, type AgentLogger, BaseAgent, type BaseAgentConfig, ConsoleLogger, type CreateSpanOptions, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, type ExecutionCycle, ExecutionCycleSchema, type Failure, type HookEventName, HookEvents, type HookHandler, HookManager, type HookPayload, type HookPayloadMap, type HookRegistration, InMemoryStore, type IterationSummary, type JsonSchemaOptions, LogLevel, MCPClient, type MCPClientOptions, type MCPServerConfig, type MCPServerConfigInput, MCPServerConfigSchema, type MCPTool, MCPToolProvider, type MCPToolProviderOptions, MCPconfig, type MaybePromise, type Memory, type MemoryCatalogEntry, type MemoryEntry, type MemoryEntryMetadata, MemoryEntryMetadataSchema, MemoryEntrySchema, type MemoryUpdate, MemoryUpdateSchema, type OpperCallOptions, type OpperCallResponse, OpperClient, type OpperClientConfig, type OpperSpan, Result, type RetryConfig, type Schema, SchemaValidationError, type SchemaValidationOptions, SilentLogger, type Success, type Thought, ThoughtSchema, type Tool, type ToolCall, type ToolCallRecord, ToolCallRecordSchema, ToolCallSchema, type ToolDefinition, type ToolExecutionContext, type ToolExecutionSummary, ToolExecutionSummarySchema, type ToolFailure, type ToolFunction, ToolMetadataSchema, type ToolOptions, type ToolProvider, type ToolResult, type ToolResultData, ToolResultFactory, ToolResultFailureSchema, type ToolResultInit, ToolResultSchema, ToolResultSuccessSchema, type ToolRunOptions, ToolRunner, type ToolSuccess, type UnregisterHook, type Usage, UsageSchema, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
1981
+ export { Agent, type AgentConfig, AgentContext, type AgentContextOptions, type AgentContextSnapshot, type AgentDecision, AgentDecisionSchema, type AgentLogger, BaseAgent, type BaseAgentConfig, ConsoleLogger, type CreateSpanOptions, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, type ExecutionCycle, ExecutionCycleSchema, type Failure, type HookEventName, HookEvents, type HookHandler, HookManager, type HookPayload, type HookPayloadMap, type HookRegistration, InMemoryStore, type IterationSummary, type JsonSchemaOptions, LogLevel, MCPClient, type MCPClientOptions, type MCPServerConfig, type MCPServerConfigInput, MCPServerConfigSchema, type MCPTool, MCPToolProvider, type MCPToolProviderOptions, MCPconfig, type MaybePromise, type Memory, type MemoryCatalogEntry, type MemoryEntry, type MemoryEntryMetadata, MemoryEntryMetadataSchema, MemoryEntrySchema, type MemoryUpdate, MemoryUpdateSchema, type OpperCallOptions, type OpperCallResponse, OpperClient, type OpperClientConfig, type OpperSpan, Result, type RetryConfig, type Schema, SchemaValidationError, type SchemaValidationOptions, SilentLogger, type Success, type Thought, ThoughtSchema, type Tool, type ToolCall, type ToolCallRecord, ToolCallRecordSchema, ToolCallSchema, type ToolDefinition, type ToolExecutionContext, type ToolExecutionSummary, ToolExecutionSummarySchema, type ToolFailure, type ToolFunction, ToolMetadataSchema, type ToolOptions, type ToolProvider, type ToolResult, type ToolResultData, ToolResultFactory, ToolResultFailureSchema, type ToolResultInit, ToolResultSchema, ToolResultSuccessSchema, type ToolRunOptions, ToolRunner, type ToolSuccess, type UnregisterHook, type Usage, UsageSchema, type VisualizationOptions, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, generateAgentFlowDiagram, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
package/dist/index.d.ts CHANGED
@@ -592,6 +592,38 @@ declare class HookManager {
592
592
  }
593
593
  declare const createHookManager: (logger?: AgentLogger) => HookManager;
594
594
 
595
+ /**
596
+ * Options for generating agent flow visualization
597
+ */
598
+ interface VisualizationOptions {
599
+ /**
600
+ * Optional file path to save the Mermaid diagram
601
+ * If provided, the diagram will be saved to this path
602
+ * .md extension will be added automatically if not present
603
+ */
604
+ outputPath?: string;
605
+ /**
606
+ * Whether to include MCP tool providers in the visualization
607
+ * When true, will show expanded tools from providers
608
+ * When false, will show providers as single nodes
609
+ * @default false
610
+ */
611
+ includeMcpTools?: boolean;
612
+ /**
613
+ * Internal parameter to track visited agents (prevents cycles)
614
+ * @internal
615
+ */
616
+ _visited?: Set<string>;
617
+ }
618
+ /**
619
+ * Generate Mermaid graph diagram for an agent's structure and flow
620
+ *
621
+ * @param agent - The agent to visualize
622
+ * @param options - Visualization options
623
+ * @returns Mermaid markdown string, or file path if outputPath was provided
624
+ */
625
+ declare function generateAgentFlowDiagram<I, O>(agent: BaseAgent<I, O>, options?: VisualizationOptions): Promise<string>;
626
+
595
627
  /**
596
628
  * Schema for memory entry metadata
597
629
  */
@@ -635,8 +667,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
635
667
  updatedAt: number;
636
668
  accessCount: number;
637
669
  };
638
- key: string;
639
670
  description: string;
671
+ key: string;
640
672
  value?: unknown;
641
673
  }, {
642
674
  metadata: {
@@ -644,8 +676,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
644
676
  updatedAt: number;
645
677
  accessCount?: number | undefined;
646
678
  };
647
- key: string;
648
679
  description: string;
680
+ key: string;
649
681
  value?: unknown;
650
682
  }>;
651
683
  type MemoryEntry = z.infer<typeof MemoryEntrySchema>;
@@ -1014,6 +1046,28 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
1014
1046
  private registerTools;
1015
1047
  private activateToolProviders;
1016
1048
  private deactivateToolProviders;
1049
+ /**
1050
+ * Generate a Mermaid flowchart diagram visualizing the agent's structure and flow.
1051
+ * Shows tools, hooks, schemas, providers, and nested agents.
1052
+ *
1053
+ * @param options - Visualization options
1054
+ * @returns Mermaid markdown string, or file path if outputPath was provided
1055
+ *
1056
+ * @example
1057
+ * ```typescript
1058
+ * // Generate diagram string
1059
+ * const diagram = await agent.visualizeFlow();
1060
+ * console.log(diagram);
1061
+ *
1062
+ * // Save to file
1063
+ * const path = await agent.visualizeFlow({ outputPath: "agent_flow.md" });
1064
+ * console.log(`Saved to ${path}`);
1065
+ *
1066
+ * // Include MCP tools details
1067
+ * const diagram = await agent.visualizeFlow({ includeMcpTools: true });
1068
+ * ```
1069
+ */
1070
+ visualizeFlow(options?: VisualizationOptions): Promise<string>;
1017
1071
  }
1018
1072
 
1019
1073
  /**
@@ -1491,9 +1545,9 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1491
1545
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1492
1546
  }, "strip", z.ZodTypeAny, {
1493
1547
  metadata: Record<string, unknown>;
1548
+ name: string;
1494
1549
  method: "GET" | "POST";
1495
1550
  headers: Record<string, string>;
1496
- name: string;
1497
1551
  timeout: number;
1498
1552
  transport: "http-sse";
1499
1553
  url: string;
@@ -1516,8 +1570,8 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1516
1570
  sessionId: z.ZodOptional<z.ZodString>;
1517
1571
  }, "strip", z.ZodTypeAny, {
1518
1572
  metadata: Record<string, unknown>;
1519
- headers: Record<string, string>;
1520
1573
  name: string;
1574
+ headers: Record<string, string>;
1521
1575
  timeout: number;
1522
1576
  transport: "streamable-http";
1523
1577
  url: string;
@@ -1575,9 +1629,9 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1575
1629
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1576
1630
  }, "strip", z.ZodTypeAny, {
1577
1631
  metadata: Record<string, unknown>;
1632
+ name: string;
1578
1633
  method: "GET" | "POST";
1579
1634
  headers: Record<string, string>;
1580
- name: string;
1581
1635
  timeout: number;
1582
1636
  transport: "http-sse";
1583
1637
  url: string;
@@ -1600,8 +1654,8 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1600
1654
  sessionId: z.ZodOptional<z.ZodString>;
1601
1655
  }, "strip", z.ZodTypeAny, {
1602
1656
  metadata: Record<string, unknown>;
1603
- headers: Record<string, string>;
1604
1657
  name: string;
1658
+ headers: Record<string, string>;
1605
1659
  timeout: number;
1606
1660
  transport: "streamable-http";
1607
1661
  url: string;
@@ -1626,16 +1680,16 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1626
1680
  stderr?: "inherit" | "pipe" | "ignore" | undefined;
1627
1681
  } | {
1628
1682
  metadata: Record<string, unknown>;
1683
+ name: string;
1629
1684
  method: "GET" | "POST";
1630
1685
  headers: Record<string, string>;
1631
- name: string;
1632
1686
  timeout: number;
1633
1687
  transport: "http-sse";
1634
1688
  url: string;
1635
1689
  } | {
1636
1690
  metadata: Record<string, unknown>;
1637
- headers: Record<string, string>;
1638
1691
  name: string;
1692
+ headers: Record<string, string>;
1639
1693
  timeout: number;
1640
1694
  transport: "streamable-http";
1641
1695
  url: string;
@@ -1924,4 +1978,4 @@ declare class ToolRunner {
1924
1978
  };
1925
1979
  }
1926
1980
 
1927
- export { Agent, type AgentConfig, AgentContext, type AgentContextOptions, type AgentContextSnapshot, type AgentDecision, AgentDecisionSchema, type AgentLogger, BaseAgent, type BaseAgentConfig, ConsoleLogger, type CreateSpanOptions, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, type ExecutionCycle, ExecutionCycleSchema, type Failure, type HookEventName, HookEvents, type HookHandler, HookManager, type HookPayload, type HookPayloadMap, type HookRegistration, InMemoryStore, type IterationSummary, type JsonSchemaOptions, LogLevel, MCPClient, type MCPClientOptions, type MCPServerConfig, type MCPServerConfigInput, MCPServerConfigSchema, type MCPTool, MCPToolProvider, type MCPToolProviderOptions, MCPconfig, type MaybePromise, type Memory, type MemoryCatalogEntry, type MemoryEntry, type MemoryEntryMetadata, MemoryEntryMetadataSchema, MemoryEntrySchema, type MemoryUpdate, MemoryUpdateSchema, type OpperCallOptions, type OpperCallResponse, OpperClient, type OpperClientConfig, type OpperSpan, Result, type RetryConfig, type Schema, SchemaValidationError, type SchemaValidationOptions, SilentLogger, type Success, type Thought, ThoughtSchema, type Tool, type ToolCall, type ToolCallRecord, ToolCallRecordSchema, ToolCallSchema, type ToolDefinition, type ToolExecutionContext, type ToolExecutionSummary, ToolExecutionSummarySchema, type ToolFailure, type ToolFunction, ToolMetadataSchema, type ToolOptions, type ToolProvider, type ToolResult, type ToolResultData, ToolResultFactory, ToolResultFailureSchema, type ToolResultInit, ToolResultSchema, ToolResultSuccessSchema, type ToolRunOptions, ToolRunner, type ToolSuccess, type UnregisterHook, type Usage, UsageSchema, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
1981
+ export { Agent, type AgentConfig, AgentContext, type AgentContextOptions, type AgentContextSnapshot, type AgentDecision, AgentDecisionSchema, type AgentLogger, BaseAgent, type BaseAgentConfig, ConsoleLogger, type CreateSpanOptions, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, type ExecutionCycle, ExecutionCycleSchema, type Failure, type HookEventName, HookEvents, type HookHandler, HookManager, type HookPayload, type HookPayloadMap, type HookRegistration, InMemoryStore, type IterationSummary, type JsonSchemaOptions, LogLevel, MCPClient, type MCPClientOptions, type MCPServerConfig, type MCPServerConfigInput, MCPServerConfigSchema, type MCPTool, MCPToolProvider, type MCPToolProviderOptions, MCPconfig, type MaybePromise, type Memory, type MemoryCatalogEntry, type MemoryEntry, type MemoryEntryMetadata, MemoryEntryMetadataSchema, MemoryEntrySchema, type MemoryUpdate, MemoryUpdateSchema, type OpperCallOptions, type OpperCallResponse, OpperClient, type OpperClientConfig, type OpperSpan, Result, type RetryConfig, type Schema, SchemaValidationError, type SchemaValidationOptions, SilentLogger, type Success, type Thought, ThoughtSchema, type Tool, type ToolCall, type ToolCallRecord, ToolCallRecordSchema, ToolCallSchema, type ToolDefinition, type ToolExecutionContext, type ToolExecutionSummary, ToolExecutionSummarySchema, type ToolFailure, type ToolFunction, ToolMetadataSchema, type ToolOptions, type ToolProvider, type ToolResult, type ToolResultData, ToolResultFactory, ToolResultFailureSchema, type ToolResultInit, ToolResultSchema, ToolResultSuccessSchema, type ToolRunOptions, ToolRunner, type ToolSuccess, type UnregisterHook, type Usage, UsageSchema, type VisualizationOptions, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, generateAgentFlowDiagram, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { z } from 'zod';
3
+ import { promises } from 'fs';
3
4
  import { Opper } from 'opperai';
4
5
  import { zodToJsonSchema } from 'zod-to-json-schema';
5
6
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
@@ -465,6 +466,229 @@ var createHookManager = (logger) => new HookManager(logger);
465
466
 
466
467
  // src/base/agent.ts
467
468
  init_tool();
469
+ function sanitizeId(name) {
470
+ return name.replace(/\s/g, "_").replace(/-/g, "_").replace(/\./g, "_").replace(/[()]/g, "");
471
+ }
472
+ function sanitizeLabel(text) {
473
+ let cleaned = text.replace(/"/g, "'").replace(/\n/g, " ").replace(/`/g, "");
474
+ cleaned = cleaned.split(".")[0]?.trim() || cleaned.trim();
475
+ if (cleaned.length > 45) {
476
+ cleaned = cleaned.substring(0, 42) + "...";
477
+ }
478
+ return cleaned;
479
+ }
480
+ function getSchemaName(schema) {
481
+ if (!schema) {
482
+ return "N/A";
483
+ }
484
+ try {
485
+ const schemaAny = schema;
486
+ if (schemaAny.description) {
487
+ return schemaAny.description;
488
+ }
489
+ if (schemaAny._def?.description) {
490
+ return schemaAny._def.description;
491
+ }
492
+ const typeName = schemaAny._def?.typeName;
493
+ if (typeName === "ZodObject" && schemaAny._def) {
494
+ const shape = schemaAny._def.shape?.();
495
+ if (shape && typeof shape === "object") {
496
+ const keys = Object.keys(shape);
497
+ if (keys.length > 0) {
498
+ const keyStr = keys.length > 3 ? `{${keys.slice(0, 3).join(", ")}...}` : `{${keys.join(", ")}}`;
499
+ return keyStr;
500
+ }
501
+ }
502
+ return "Object";
503
+ }
504
+ if (typeName) {
505
+ return typeName.replace("Zod", "").replace("Type", "");
506
+ }
507
+ return "Any";
508
+ } catch {
509
+ return "Any";
510
+ }
511
+ }
512
+ function extractParameters(schema) {
513
+ if (!schema) {
514
+ return null;
515
+ }
516
+ try {
517
+ const schemaAny = schema;
518
+ if (schemaAny._def?.typeName === "ZodObject") {
519
+ const shape = schemaAny._def.shape?.();
520
+ if (shape && typeof shape === "object") {
521
+ const params = [];
522
+ for (const [key, value] of Object.entries(shape)) {
523
+ const fieldType = value?._def?.typeName;
524
+ if (fieldType) {
525
+ const cleanType = fieldType.replace("Zod", "").toLowerCase();
526
+ params.push(`${key}: ${cleanType}`);
527
+ } else {
528
+ params.push(key);
529
+ }
530
+ }
531
+ return params.length > 0 ? params : null;
532
+ }
533
+ }
534
+ return null;
535
+ } catch {
536
+ return null;
537
+ }
538
+ }
539
+ function getRegisteredHooks(hooks) {
540
+ const events = [];
541
+ const allEvents = Object.values(HookEvents);
542
+ for (const event of allEvents) {
543
+ if (hooks.listenerCount(event) > 0) {
544
+ events.push(event);
545
+ }
546
+ }
547
+ return events;
548
+ }
549
+ function getWrappedAgent(tool2) {
550
+ const wrapped = tool2.metadata?.["wrappedAgent"];
551
+ if (wrapped && typeof wrapped === "object" && "name" in wrapped) {
552
+ return wrapped;
553
+ }
554
+ return null;
555
+ }
556
+ function isMcpTool(tool2) {
557
+ return tool2.metadata?.["provider"] === "mcp";
558
+ }
559
+ async function generateAgentFlowDiagram(agent, options = {}) {
560
+ const visited = options._visited ?? /* @__PURE__ */ new Set();
561
+ const isRoot = visited.size === 0;
562
+ const lines = [];
563
+ if (isRoot) {
564
+ lines.push("```mermaid");
565
+ lines.push("graph TB");
566
+ }
567
+ const agentId = sanitizeId(agent.name);
568
+ if (visited.has(agentId)) {
569
+ return "";
570
+ }
571
+ visited.add(agentId);
572
+ let agentLabel = `\u{1F916} ${agent.name}`;
573
+ if (agent.description && agent.description !== `Agent: ${agent.name}` && agent.description !== agent.name) {
574
+ const desc = sanitizeLabel(agent.description);
575
+ agentLabel += `<br/><i>${desc}</i>`;
576
+ }
577
+ const inputSchemaName = getSchemaName(agent.inputSchema);
578
+ const outputSchemaName = getSchemaName(agent.outputSchema);
579
+ agentLabel += `<br/>In: ${inputSchemaName} | Out: ${outputSchemaName}`;
580
+ lines.push(` ${agentId}["${agentLabel}"]:::agent`);
581
+ const agentWithHooks = agent;
582
+ const registeredHooks = getRegisteredHooks(agentWithHooks.hooks);
583
+ if (registeredHooks.length > 0) {
584
+ const hookId = `${agentId}_hooks`;
585
+ const hookNames = registeredHooks.slice(0, 3).join(", ");
586
+ const hookLabel = registeredHooks.length > 3 ? `${hookNames} +${registeredHooks.length - 3}` : hookNames;
587
+ lines.push(` ${hookId}["\u{1FA9D} ${hookLabel}"]:::hook`);
588
+ lines.push(` ${agentId} -.-> ${hookId}`);
589
+ }
590
+ const tools = agent.getTools();
591
+ const regularTools = [];
592
+ const mcpToolsByServer = /* @__PURE__ */ new Map();
593
+ const agentTools = [];
594
+ for (const tool2 of tools) {
595
+ const wrappedAgent = getWrappedAgent(tool2);
596
+ if (wrappedAgent) {
597
+ agentTools.push(tool2);
598
+ } else if (isMcpTool(tool2)) {
599
+ const serverName = tool2.metadata?.["server"] ?? "unknown";
600
+ const serverTools = mcpToolsByServer.get(serverName) ?? [];
601
+ serverTools.push(tool2);
602
+ mcpToolsByServer.set(serverName, serverTools);
603
+ } else {
604
+ regularTools.push(tool2);
605
+ }
606
+ }
607
+ for (const tool2 of regularTools) {
608
+ const toolId = sanitizeId(`${agentId}_${tool2.name}`);
609
+ let toolLabel = `\u2699\uFE0F ${sanitizeLabel(tool2.name)}`;
610
+ if (tool2.description) {
611
+ const desc = sanitizeLabel(tool2.description);
612
+ toolLabel += `<br/><i>${desc}</i>`;
613
+ }
614
+ const params = extractParameters(tool2.schema);
615
+ if (params && params.length > 0) {
616
+ const paramsStr = params.length > 3 ? `${params.slice(0, 3).join(", ")}...` : params.join(", ");
617
+ toolLabel += `<br/>(${paramsStr})`;
618
+ }
619
+ lines.push(` ${toolId}["${toolLabel}"]:::tool`);
620
+ lines.push(` ${agentId} --> ${toolId}`);
621
+ }
622
+ if (mcpToolsByServer.size > 0) {
623
+ for (const [serverName, serverTools] of mcpToolsByServer.entries()) {
624
+ if (options.includeMcpTools) {
625
+ for (const tool2 of serverTools) {
626
+ const toolId = sanitizeId(`${agentId}_${tool2.name}`);
627
+ let toolLabel = `\u2699\uFE0F ${sanitizeLabel(tool2.name)}`;
628
+ if (tool2.description) {
629
+ const desc = sanitizeLabel(tool2.description);
630
+ toolLabel += `<br/><i>${desc}</i>`;
631
+ }
632
+ toolLabel += `<br/>(MCP: ${sanitizeLabel(serverName)})`;
633
+ lines.push(` ${toolId}["${toolLabel}"]:::tool`);
634
+ lines.push(` ${agentId} --> ${toolId}`);
635
+ }
636
+ } else {
637
+ const providerId = sanitizeId(`${agentId}_provider_${serverName}`);
638
+ lines.push(` ${providerId}["\u{1F50C} ${serverName}"]:::provider`);
639
+ lines.push(` ${agentId} --> ${providerId}`);
640
+ }
641
+ }
642
+ }
643
+ for (const tool2 of agentTools) {
644
+ const wrappedAgent = getWrappedAgent(tool2);
645
+ if (wrappedAgent) {
646
+ const subAgentId = sanitizeId(wrappedAgent.name);
647
+ lines.push(` ${agentId} --> ${subAgentId}`);
648
+ const subDiagram = await generateAgentFlowDiagram(wrappedAgent, {
649
+ ...options,
650
+ _visited: visited
651
+ });
652
+ const subLines = subDiagram.split("\n").filter(
653
+ (line) => line && !line.includes("```mermaid") && !line.includes("```") && !line.includes("%% Styling") && !line.includes("classDef")
654
+ );
655
+ lines.push(...subLines);
656
+ }
657
+ }
658
+ if (isRoot) {
659
+ lines.push("");
660
+ lines.push(" %% Styling - Opper Brand Colors");
661
+ lines.push(
662
+ " classDef agent fill:#8CF0DC,stroke:#1B2E40,stroke-width:3px,color:#1B2E40"
663
+ );
664
+ lines.push(
665
+ " classDef tool fill:#FFD7D7,stroke:#3C3CAF,stroke-width:2px,color:#1B2E40"
666
+ );
667
+ lines.push(
668
+ " classDef schema fill:#F8F8F8,stroke:#3C3CAF,stroke-width:2px,color:#1B2E40"
669
+ );
670
+ lines.push(
671
+ " classDef hook fill:#FFB186,stroke:#3C3CAF,stroke-width:2px,color:#1B2E40"
672
+ );
673
+ lines.push(
674
+ " classDef provider fill:#8CECF2,stroke:#1B2E40,stroke-width:2px,color:#1B2E40"
675
+ );
676
+ lines.push("```");
677
+ }
678
+ const diagram = lines.join("\n");
679
+ if (options.outputPath && isRoot) {
680
+ let filePath = options.outputPath;
681
+ if (!filePath.endsWith(".md")) {
682
+ filePath += ".md";
683
+ }
684
+ const fileContent = `# Agent Flow: ${agent.name}
685
+
686
+ ${diagram}`;
687
+ await promises.writeFile(filePath, fileContent, "utf-8");
688
+ return filePath;
689
+ }
690
+ return diagram;
691
+ }
468
692
  var MemoryEntryMetadataSchema = z.object({
469
693
  createdAt: z.number(),
470
694
  updatedAt: z.number(),
@@ -798,7 +1022,9 @@ var BaseAgent = class {
798
1022
  ...this.inputSchema && { schema: this.inputSchema },
799
1023
  metadata: {
800
1024
  isAgent: true,
801
- agentName: this.name
1025
+ agentName: this.name,
1026
+ wrappedAgent: this
1027
+ // Store reference to this agent for visualization
802
1028
  },
803
1029
  execute: async (input, executionContext) => {
804
1030
  try {
@@ -996,6 +1222,30 @@ var BaseAgent = class {
996
1222
  });
997
1223
  await Promise.allSettled(teardownPromises);
998
1224
  }
1225
+ /**
1226
+ * Generate a Mermaid flowchart diagram visualizing the agent's structure and flow.
1227
+ * Shows tools, hooks, schemas, providers, and nested agents.
1228
+ *
1229
+ * @param options - Visualization options
1230
+ * @returns Mermaid markdown string, or file path if outputPath was provided
1231
+ *
1232
+ * @example
1233
+ * ```typescript
1234
+ * // Generate diagram string
1235
+ * const diagram = await agent.visualizeFlow();
1236
+ * console.log(diagram);
1237
+ *
1238
+ * // Save to file
1239
+ * const path = await agent.visualizeFlow({ outputPath: "agent_flow.md" });
1240
+ * console.log(`Saved to ${path}`);
1241
+ *
1242
+ * // Include MCP tools details
1243
+ * const diagram = await agent.visualizeFlow({ includeMcpTools: true });
1244
+ * ```
1245
+ */
1246
+ async visualizeFlow(options) {
1247
+ return generateAgentFlowDiagram(this, options);
1248
+ }
999
1249
  };
1000
1250
 
1001
1251
  // src/index.ts
@@ -1085,6 +1335,20 @@ var ToolExecutionSummarySchema = z.object({
1085
1335
  */
1086
1336
  error: z.string().optional()
1087
1337
  });
1338
+
1339
+ // package.json
1340
+ var package_default = {
1341
+ version: "0.1.3"};
1342
+
1343
+ // src/utils/version.ts
1344
+ var SDK_NAME = "@opperai/agents";
1345
+ var SDK_VERSION = package_default.version;
1346
+ var SDK_PLATFORM = "ts";
1347
+ function getUserAgent() {
1348
+ return `${SDK_NAME}-${SDK_PLATFORM}/${SDK_VERSION}`;
1349
+ }
1350
+
1351
+ // src/opper/client.ts
1088
1352
  var isPlainRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1089
1353
  var isZodSchema = (value) => typeof value === "object" && value !== null && "_def" in value && typeof value.parse === "function";
1090
1354
  var readTokenCount = (usage, key) => {
@@ -1121,7 +1385,8 @@ var OpperClient = class {
1121
1385
  retryConfig;
1122
1386
  constructor(apiKey, options = {}) {
1123
1387
  this.client = new Opper({
1124
- httpBearer: apiKey ?? process.env["OPPER_HTTP_BEARER"] ?? ""
1388
+ httpBearer: apiKey ?? process.env["OPPER_HTTP_BEARER"] ?? "",
1389
+ userAgent: getUserAgent()
1125
1390
  });
1126
1391
  this.logger = options.logger ?? getDefaultLogger();
1127
1392
  this.retryConfig = {
@@ -2611,6 +2876,6 @@ var ToolRunner = class {
2611
2876
  }
2612
2877
  };
2613
2878
 
2614
- export { Agent, AgentContext, AgentDecisionSchema, BaseAgent, ConsoleLogger, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, ExecutionCycleSchema, HookEvents, HookManager, InMemoryStore, LogLevel, MCPClient, MCPServerConfigSchema, MCPToolProvider, MCPconfig, MemoryEntryMetadataSchema, MemoryEntrySchema, MemoryUpdateSchema, OpperClient, Result, SchemaValidationError, SilentLogger, ThoughtSchema, ToolCallRecordSchema, ToolCallSchema, ToolExecutionSummarySchema, ToolMetadataSchema, ToolResultFactory, ToolResultFailureSchema, ToolResultSchema, ToolResultSuccessSchema, ToolRunner, UsageSchema, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
2879
+ export { Agent, AgentContext, AgentDecisionSchema, BaseAgent, ConsoleLogger, DEFAULT_MODEL, DEFAULT_RETRY_CONFIG, ExecutionCycleSchema, HookEvents, HookManager, InMemoryStore, LogLevel, MCPClient, MCPServerConfigSchema, MCPToolProvider, MCPconfig, MemoryEntryMetadataSchema, MemoryEntrySchema, MemoryUpdateSchema, OpperClient, Result, SchemaValidationError, SilentLogger, ThoughtSchema, ToolCallRecordSchema, ToolCallSchema, ToolExecutionSummarySchema, ToolMetadataSchema, ToolResultFactory, ToolResultFailureSchema, ToolResultSchema, ToolResultSuccessSchema, ToolRunner, UsageSchema, coerceToolDefinition, createFunctionTool, createHookManager, createInMemoryStore, createMCPServerConfig, createOpperClient, createToolCallRecord, err, extractTools, generateAgentFlowDiagram, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };
2615
2880
  //# sourceMappingURL=index.js.map
2616
2881
  //# sourceMappingURL=index.js.map