@opperai/agents 0.1.1 → 0.2.0

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.ts CHANGED
@@ -508,6 +508,10 @@ declare const HookEvents: {
508
508
  readonly MemoryRead: "memory:read";
509
509
  readonly MemoryWrite: "memory:write";
510
510
  readonly MemoryError: "memory:error";
511
+ readonly StreamStart: "stream:start";
512
+ readonly StreamChunk: "stream:chunk";
513
+ readonly StreamEnd: "stream:end";
514
+ readonly StreamError: "stream:error";
511
515
  };
512
516
  type HookEventName = (typeof HookEvents)[keyof typeof HookEvents];
513
517
  interface HookPayloadMap {
@@ -533,6 +537,7 @@ interface HookPayloadMap {
533
537
  context: AgentContext;
534
538
  callType: string;
535
539
  response: unknown;
540
+ parsed?: unknown;
536
541
  };
537
542
  [HookEvents.ThinkEnd]: {
538
543
  context: AgentContext;
@@ -570,6 +575,31 @@ interface HookPayloadMap {
570
575
  operation: "read" | "write" | "delete" | "clear";
571
576
  error: unknown;
572
577
  };
578
+ [HookEvents.StreamStart]: {
579
+ context: AgentContext;
580
+ callType: string;
581
+ };
582
+ [HookEvents.StreamChunk]: {
583
+ context: AgentContext;
584
+ callType: string;
585
+ chunkData: {
586
+ delta: unknown;
587
+ jsonPath?: string | null;
588
+ chunkType?: string | null;
589
+ };
590
+ accumulated: string;
591
+ fieldBuffers: Record<string, string>;
592
+ };
593
+ [HookEvents.StreamEnd]: {
594
+ context: AgentContext;
595
+ callType: string;
596
+ fieldBuffers: Record<string, string>;
597
+ };
598
+ [HookEvents.StreamError]: {
599
+ context: AgentContext;
600
+ callType: string;
601
+ error: unknown;
602
+ };
573
603
  }
574
604
  type HookPayload<E extends HookEventName> = HookPayloadMap[E];
575
605
  type HookHandler<E extends HookEventName> = (payload: HookPayload<E>) => void | Promise<void>;
@@ -592,6 +622,60 @@ declare class HookManager {
592
622
  }
593
623
  declare const createHookManager: (logger?: AgentLogger) => HookManager;
594
624
 
625
+ declare const AgentEvents: {
626
+ readonly StreamStart: "stream:start";
627
+ readonly StreamChunk: "stream:chunk";
628
+ readonly StreamEnd: "stream:end";
629
+ readonly StreamError: "stream:error";
630
+ };
631
+ type AgentEventName = (typeof AgentEvents)[keyof typeof AgentEvents];
632
+ type AgentEventPayloadMap = Pick<HookPayloadMap, AgentEventName>;
633
+ type AgentEventPayload<E extends AgentEventName> = AgentEventPayloadMap[E];
634
+ type AgentEventListener<E extends AgentEventName> = (payload: AgentEventPayload<E>) => void;
635
+ declare class AgentEventEmitter {
636
+ private readonly registry;
637
+ private readonly logger;
638
+ constructor(logger?: AgentLogger);
639
+ on<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): () => void;
640
+ once<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): () => void;
641
+ off<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): void;
642
+ emit<E extends AgentEventName>(event: E, payload: AgentEventPayload<E>): void;
643
+ removeAllListeners(event?: AgentEventName): void;
644
+ listenerCount(event?: AgentEventName): number;
645
+ }
646
+
647
+ /**
648
+ * Options for generating agent flow visualization
649
+ */
650
+ interface VisualizationOptions {
651
+ /**
652
+ * Optional file path to save the Mermaid diagram
653
+ * If provided, the diagram will be saved to this path
654
+ * .md extension will be added automatically if not present
655
+ */
656
+ outputPath?: string;
657
+ /**
658
+ * Whether to include MCP tool providers in the visualization
659
+ * When true, will show expanded tools from providers
660
+ * When false, will show providers as single nodes
661
+ * @default false
662
+ */
663
+ includeMcpTools?: boolean;
664
+ /**
665
+ * Internal parameter to track visited agents (prevents cycles)
666
+ * @internal
667
+ */
668
+ _visited?: Set<string>;
669
+ }
670
+ /**
671
+ * Generate Mermaid graph diagram for an agent's structure and flow
672
+ *
673
+ * @param agent - The agent to visualize
674
+ * @param options - Visualization options
675
+ * @returns Mermaid markdown string, or file path if outputPath was provided
676
+ */
677
+ declare function generateAgentFlowDiagram<I, O>(agent: BaseAgent<I, O>, options?: VisualizationOptions): Promise<string>;
678
+
595
679
  /**
596
680
  * Schema for memory entry metadata
597
681
  */
@@ -635,8 +719,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
635
719
  updatedAt: number;
636
720
  accessCount: number;
637
721
  };
638
- key: string;
639
722
  description: string;
723
+ key: string;
640
724
  value?: unknown;
641
725
  }, {
642
726
  metadata: {
@@ -644,8 +728,8 @@ declare const MemoryEntrySchema: z.ZodObject<{
644
728
  updatedAt: number;
645
729
  accessCount?: number | undefined;
646
730
  };
647
- key: string;
648
731
  description: string;
732
+ key: string;
649
733
  value?: unknown;
650
734
  }>;
651
735
  type MemoryEntry = z.infer<typeof MemoryEntrySchema>;
@@ -793,6 +877,27 @@ interface BaseAgentConfig<TInput, TOutput> {
793
877
  * Output schema for validation (Zod schema)
794
878
  */
795
879
  outputSchema?: ZodType<TOutput>;
880
+ /**
881
+ * Enable Opper streaming APIs for LLM calls
882
+ * @default false
883
+ */
884
+ enableStreaming?: boolean;
885
+ /**
886
+ * Register a handler invoked when a streaming call starts.
887
+ */
888
+ onStreamStart?: AgentEventListener<typeof HookEvents.StreamStart>;
889
+ /**
890
+ * Register a handler invoked for each streaming chunk.
891
+ */
892
+ onStreamChunk?: AgentEventListener<typeof HookEvents.StreamChunk>;
893
+ /**
894
+ * Register a handler invoked when a streaming call ends.
895
+ */
896
+ onStreamEnd?: AgentEventListener<typeof HookEvents.StreamEnd>;
897
+ /**
898
+ * Register a handler invoked when streaming encounters an error.
899
+ */
900
+ onStreamError?: AgentEventListener<typeof HookEvents.StreamError>;
796
901
  /**
797
902
  * Enable memory subsystem
798
903
  * @default false
@@ -868,6 +973,10 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
868
973
  * Whether memory is enabled
869
974
  */
870
975
  readonly enableMemory: boolean;
976
+ /**
977
+ * Whether streaming is enabled
978
+ */
979
+ readonly enableStreaming: boolean;
871
980
  /**
872
981
  * Memory instance for persistent storage (null if disabled or initialization failed)
873
982
  */
@@ -880,6 +989,10 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
880
989
  * Hook manager for lifecycle events
881
990
  */
882
991
  protected readonly hooks: HookManager;
992
+ /**
993
+ * Event dispatcher for runtime events (notably streaming)
994
+ */
995
+ protected readonly events: AgentEventEmitter;
883
996
  /**
884
997
  * Registry of available tools
885
998
  */
@@ -990,6 +1103,29 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
990
1103
  * @returns Cleanup function to unregister the hook
991
1104
  */
992
1105
  registerHook<E extends HookEventName>(event: E, handler: HookHandler<E>): () => void;
1106
+ /**
1107
+ * Register an event listener.
1108
+ *
1109
+ * @param event - Event name
1110
+ * @param listener - Listener callback
1111
+ * @returns Cleanup function to unregister the listener
1112
+ */
1113
+ on<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): () => void;
1114
+ /**
1115
+ * Register a one-time event listener that removes itself after the first call.
1116
+ *
1117
+ * @param event - Event name
1118
+ * @param listener - Listener callback
1119
+ * @returns Cleanup function (no-op once listener fires)
1120
+ */
1121
+ once<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): () => void;
1122
+ /**
1123
+ * Remove a previously registered event listener.
1124
+ *
1125
+ * @param event - Event name
1126
+ * @param listener - Listener callback to remove
1127
+ */
1128
+ off<E extends AgentEventName>(event: E, listener: AgentEventListener<E>): void;
993
1129
  /**
994
1130
  * Trigger a hook event with a payload.
995
1131
  * Swallows errors to prevent hook failures from breaking agent execution.
@@ -998,6 +1134,13 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
998
1134
  * @param payload - Event payload
999
1135
  */
1000
1136
  protected triggerHook<E extends HookEventName>(event: E, payload: Parameters<HookHandler<E>>[0]): Promise<void>;
1137
+ /**
1138
+ * Emit a runtime event to listeners.
1139
+ *
1140
+ * @param event - Event name
1141
+ * @param payload - Event payload
1142
+ */
1143
+ protected emitAgentEvent<E extends AgentEventName>(event: E, payload: AgentEventPayload<E>): void;
1001
1144
  /**
1002
1145
  * Execute a tool with proper context, hooks, and error handling.
1003
1146
  *
@@ -1014,8 +1157,55 @@ declare abstract class BaseAgent<TInput = unknown, TOutput = unknown> {
1014
1157
  private registerTools;
1015
1158
  private activateToolProviders;
1016
1159
  private deactivateToolProviders;
1160
+ /**
1161
+ * Generate a Mermaid flowchart diagram visualizing the agent's structure and flow.
1162
+ * Shows tools, hooks, schemas, providers, and nested agents.
1163
+ *
1164
+ * @param options - Visualization options
1165
+ * @returns Mermaid markdown string, or file path if outputPath was provided
1166
+ *
1167
+ * @example
1168
+ * ```typescript
1169
+ * // Generate diagram string
1170
+ * const diagram = await agent.visualizeFlow();
1171
+ * console.log(diagram);
1172
+ *
1173
+ * // Save to file
1174
+ * const path = await agent.visualizeFlow({ outputPath: "agent_flow.md" });
1175
+ * console.log(`Saved to ${path}`);
1176
+ *
1177
+ * // Include MCP tools details
1178
+ * const diagram = await agent.visualizeFlow({ includeMcpTools: true });
1179
+ * ```
1180
+ */
1181
+ visualizeFlow(options?: VisualizationOptions): Promise<string>;
1017
1182
  }
1018
1183
 
1184
+ /**
1185
+ * Streaming chunk payload from Opper SSE responses.
1186
+ */
1187
+ interface OpperStreamChunk {
1188
+ delta?: string | number | boolean | null | undefined;
1189
+ jsonPath?: string | null | undefined;
1190
+ spanId?: string | null | undefined;
1191
+ chunkType?: string | null | undefined;
1192
+ }
1193
+ /**
1194
+ * Server-sent event emitted during streaming calls.
1195
+ */
1196
+ interface OpperStreamEvent {
1197
+ id?: string;
1198
+ event?: string;
1199
+ retry?: number;
1200
+ data?: OpperStreamChunk;
1201
+ }
1202
+ /**
1203
+ * Structured response returned by Opper stream endpoints.
1204
+ */
1205
+ interface OpperStreamResponse {
1206
+ headers: Record<string, string[]>;
1207
+ result: AsyncIterable<OpperStreamEvent>;
1208
+ }
1019
1209
  /**
1020
1210
  * Opper call response
1021
1211
  */
@@ -1079,6 +1269,10 @@ interface OpperCallOptions<TInput = unknown, TOutput = unknown> {
1079
1269
  * Parent span ID for tracing
1080
1270
  */
1081
1271
  parentSpanId?: string;
1272
+ /**
1273
+ * Abort signal used to cancel the underlying HTTP request.
1274
+ */
1275
+ signal?: AbortSignal;
1082
1276
  }
1083
1277
  /**
1084
1278
  * Span information
@@ -1137,6 +1331,10 @@ declare class OpperClient {
1137
1331
  * Make a call to Opper with retry logic
1138
1332
  */
1139
1333
  call<TInput = unknown, TOutput = unknown>(options: OpperCallOptions<TInput, TOutput>): Promise<OpperCallResponse<TOutput>>;
1334
+ /**
1335
+ * Stream a call to Opper with retry logic
1336
+ */
1337
+ stream<TInput = unknown, TOutput = unknown>(options: OpperCallOptions<TInput, TOutput>): Promise<OpperStreamResponse>;
1140
1338
  /**
1141
1339
  * Create a span for tracing
1142
1340
  */
@@ -1214,6 +1412,7 @@ declare class Agent<TInput = unknown, TOutput = unknown> extends BaseAgent<TInpu
1214
1412
  * Think step: Call LLM to decide next action
1215
1413
  */
1216
1414
  private think;
1415
+ private thinkStreaming;
1217
1416
  /**
1218
1417
  * Build static instructions for the think step
1219
1418
  */
@@ -1235,6 +1434,8 @@ declare class Agent<TInput = unknown, TOutput = unknown> extends BaseAgent<TInpu
1235
1434
  * Generate final result based on execution history
1236
1435
  */
1237
1436
  private generateFinalResult;
1437
+ private generateFinalResultStreaming;
1438
+ private trackStreamingUsageBySpan;
1238
1439
  /**
1239
1440
  * Log helper
1240
1441
  */
@@ -1491,9 +1692,9 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1491
1692
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1492
1693
  }, "strip", z.ZodTypeAny, {
1493
1694
  metadata: Record<string, unknown>;
1695
+ name: string;
1494
1696
  method: "GET" | "POST";
1495
1697
  headers: Record<string, string>;
1496
- name: string;
1497
1698
  timeout: number;
1498
1699
  transport: "http-sse";
1499
1700
  url: string;
@@ -1516,8 +1717,8 @@ declare const MCPConfigVariants: z.ZodDiscriminatedUnion<"transport", [z.ZodObje
1516
1717
  sessionId: z.ZodOptional<z.ZodString>;
1517
1718
  }, "strip", z.ZodTypeAny, {
1518
1719
  metadata: Record<string, unknown>;
1519
- headers: Record<string, string>;
1520
1720
  name: string;
1721
+ headers: Record<string, string>;
1521
1722
  timeout: number;
1522
1723
  transport: "streamable-http";
1523
1724
  url: string;
@@ -1575,9 +1776,9 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1575
1776
  method: z.ZodDefault<z.ZodEnum<["GET", "POST"]>>;
1576
1777
  }, "strip", z.ZodTypeAny, {
1577
1778
  metadata: Record<string, unknown>;
1779
+ name: string;
1578
1780
  method: "GET" | "POST";
1579
1781
  headers: Record<string, string>;
1580
- name: string;
1581
1782
  timeout: number;
1582
1783
  transport: "http-sse";
1583
1784
  url: string;
@@ -1600,8 +1801,8 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1600
1801
  sessionId: z.ZodOptional<z.ZodString>;
1601
1802
  }, "strip", z.ZodTypeAny, {
1602
1803
  metadata: Record<string, unknown>;
1603
- headers: Record<string, string>;
1604
1804
  name: string;
1805
+ headers: Record<string, string>;
1605
1806
  timeout: number;
1606
1807
  transport: "streamable-http";
1607
1808
  url: string;
@@ -1626,16 +1827,16 @@ declare const MCPServerConfigSchema: z.ZodEffects<z.ZodDiscriminatedUnion<"trans
1626
1827
  stderr?: "inherit" | "pipe" | "ignore" | undefined;
1627
1828
  } | {
1628
1829
  metadata: Record<string, unknown>;
1830
+ name: string;
1629
1831
  method: "GET" | "POST";
1630
1832
  headers: Record<string, string>;
1631
- name: string;
1632
1833
  timeout: number;
1633
1834
  transport: "http-sse";
1634
1835
  url: string;
1635
1836
  } | {
1636
1837
  metadata: Record<string, unknown>;
1637
- headers: Record<string, string>;
1638
1838
  name: string;
1839
+ headers: Record<string, string>;
1639
1840
  timeout: number;
1640
1841
  transport: "streamable-http";
1641
1842
  url: string;
@@ -1739,6 +1940,37 @@ declare const schemaToJson: (schema: ZodTypeAny, options?: JsonSchemaOptions) =>
1739
1940
  declare const getSchemaDefault: <T>(schema: Schema<T>) => T | undefined;
1740
1941
  declare const mergeSchemaDefaults: <T extends Record<string, unknown>>(schema: Schema<T>, value: Partial<T>) => T;
1741
1942
 
1943
+ declare const STREAM_ROOT_PATH = "_root";
1944
+ interface StreamAssemblerOptions {
1945
+ schema?: ZodTypeAny;
1946
+ }
1947
+ interface StreamFeedResult {
1948
+ path: string;
1949
+ accumulated: string;
1950
+ snapshot: Record<string, string>;
1951
+ }
1952
+ interface StreamFinalizeResult {
1953
+ type: "root" | "structured" | "empty";
1954
+ rootText?: string;
1955
+ structured?: unknown;
1956
+ }
1957
+ declare class StreamAssembler {
1958
+ private readonly displayBuffers;
1959
+ private readonly valueBuffers;
1960
+ private readonly schema;
1961
+ constructor(options?: StreamAssemblerOptions);
1962
+ feed(chunk: {
1963
+ delta?: unknown;
1964
+ jsonPath?: string | null | undefined;
1965
+ }): StreamFeedResult | null;
1966
+ snapshot(): Record<string, string>;
1967
+ hasStructuredFields(): boolean;
1968
+ finalize(): StreamFinalizeResult;
1969
+ getFieldBuffers(): Map<string, string>;
1970
+ private reconstructStructured;
1971
+ }
1972
+ declare const createStreamAssembler: (options?: StreamAssemblerOptions) => StreamAssembler;
1973
+
1742
1974
  /**
1743
1975
  * Options for creating a tool from a function
1744
1976
  */
@@ -1924,4 +2156,4 @@ declare class ToolRunner {
1924
2156
  };
1925
2157
  }
1926
2158
 
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 };
2159
+ export { Agent, type AgentConfig, AgentContext, type AgentContextOptions, type AgentContextSnapshot, type AgentDecision, AgentDecisionSchema, AgentEventEmitter, type AgentEventListener, type AgentEventName, type AgentEventPayload, type AgentEventPayloadMap, AgentEvents, 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, type OpperStreamChunk, type OpperStreamEvent, type OpperStreamResponse, Result, type RetryConfig, STREAM_ROOT_PATH, type Schema, SchemaValidationError, type SchemaValidationOptions, SilentLogger, StreamAssembler, type StreamAssemblerOptions, type StreamFeedResult, type StreamFinalizeResult, 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, createStreamAssembler, createToolCallRecord, err, extractTools, generateAgentFlowDiagram, getDefaultLogger, getSchemaDefault, isSchemaValid, isToolProvider, mcp, mergeSchemaDefaults, normalizeToolEntries, ok, schemaToJson, setDefaultLogger, tool, validateSchema, validateToolInput };