@runflow-ai/sdk 1.0.32 → 1.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +354 -19
  2. package/dist/core/agent.d.ts.map +1 -1
  3. package/dist/core/agent.js +76 -15
  4. package/dist/core/agent.js.map +1 -1
  5. package/dist/core/helpers/agent-memory.d.ts +2 -2
  6. package/dist/core/helpers/agent-memory.d.ts.map +1 -1
  7. package/dist/core/helpers/agent-memory.js +17 -4
  8. package/dist/core/helpers/agent-memory.js.map +1 -1
  9. package/dist/core/helpers/agent-rag.d.ts.map +1 -1
  10. package/dist/core/helpers/agent-rag.js +4 -0
  11. package/dist/core/helpers/agent-rag.js.map +1 -1
  12. package/dist/core/helpers/observability-helpers.d.ts +33 -0
  13. package/dist/core/helpers/observability-helpers.d.ts.map +1 -0
  14. package/dist/core/helpers/observability-helpers.js +112 -0
  15. package/dist/core/helpers/observability-helpers.js.map +1 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +14 -6
  19. package/dist/index.js.map +1 -1
  20. package/dist/observability/execution.d.ts +44 -0
  21. package/dist/observability/execution.d.ts.map +1 -0
  22. package/dist/observability/execution.js +147 -0
  23. package/dist/observability/execution.js.map +1 -0
  24. package/dist/observability/identify.d.ts +37 -0
  25. package/dist/observability/identify.d.ts.map +1 -0
  26. package/dist/observability/identify.js +124 -0
  27. package/dist/observability/identify.js.map +1 -0
  28. package/dist/observability/index.d.ts +7 -0
  29. package/dist/observability/index.d.ts.map +1 -1
  30. package/dist/observability/index.js +20 -2
  31. package/dist/observability/index.js.map +1 -1
  32. package/dist/observability/logging.d.ts +52 -0
  33. package/dist/observability/logging.d.ts.map +1 -0
  34. package/dist/observability/logging.js +140 -0
  35. package/dist/observability/logging.js.map +1 -0
  36. package/dist/observability/trace-collector.d.ts +14 -2
  37. package/dist/observability/trace-collector.d.ts.map +1 -1
  38. package/dist/observability/trace-collector.js +151 -3
  39. package/dist/observability/trace-collector.js.map +1 -1
  40. package/dist/types/all-types.d.ts +12 -0
  41. package/dist/types/all-types.d.ts.map +1 -1
  42. package/package.json +1 -1
package/README.md CHANGED
@@ -401,43 +401,83 @@ await agent.process({
401
401
  });
402
402
  ```
403
403
 
404
- #### Identification Types
404
+ #### Smart Identification (Auto-Detection)
405
+
406
+ **New in v2.1:** The `identify()` function now auto-detects entity type from value format:
405
407
 
406
408
  ```typescript
407
- // WhatsApp/SMS (by phone)
408
- Runflow.identify({
409
- type: 'phone',
410
- value: '+5511999999999',
411
- });
409
+ import { identify } from '@runflow-ai/sdk/observability';
412
410
 
413
- // Email
414
- Runflow.identify({
415
- type: 'email',
416
- value: 'user@example.com',
417
- });
411
+ // Auto-detect email
412
+ identify('user@example.com');
413
+ // → type: 'email', value: 'user@example.com'
414
+
415
+ // Auto-detect phone (international)
416
+ identify('+5511999999999');
417
+ // → type: 'phone', value: '+5511999999999'
418
+
419
+ // Auto-detect phone (local with formatting)
420
+ identify('(11) 99999-9999');
421
+ // → type: 'phone', value: '(11) 99999-9999'
422
+
423
+ // Auto-detect UUID
424
+ identify('550e8400-e29b-41d4-a716-446655440000');
425
+ // → type: 'uuid'
426
+
427
+ // Auto-detect URL
428
+ identify('https://example.com');
429
+ // → type: 'url'
430
+ ```
431
+
432
+ **Supported patterns:**
433
+ - **Email**: Standard RFC 5322 format
434
+ - **Phone**: E.164 format (with/without +, with/without formatting)
435
+ - **UUID**: Standard UUID v1-v5
436
+ - **URL**: With or without protocol
437
+ - **Fallback**: Generic `id` type for custom identifiers
438
+
439
+ #### Explicit Identification
440
+
441
+ For custom entity types or when auto-detection is not desired:
442
+
443
+ ```typescript
444
+ import { identify } from '@runflow-ai/sdk/observability';
418
445
 
419
446
  // HubSpot Contact
420
- Runflow.identify({
447
+ identify({
421
448
  type: 'hubspot_contact',
422
449
  value: 'contact_123',
423
450
  userId: 'user@example.com',
424
451
  });
425
452
 
426
- // Custom (order, ticket, etc)
427
- Runflow.identify({
453
+ // Order/Ticket
454
+ identify({
428
455
  type: 'order',
429
- value: 'order_456',
456
+ value: 'ORDER-456',
430
457
  userId: 'customer_789',
431
458
  });
432
459
 
433
- // With custom threadId
434
- Runflow.identify({
435
- type: 'phone',
436
- value: '+5511999999999',
460
+ // Custom threadId override
461
+ identify({
462
+ type: 'document',
463
+ value: 'doc_456',
437
464
  threadId: 'custom_thread_123',
438
465
  });
439
466
  ```
440
467
 
468
+ #### Backward Compatibility
469
+
470
+ The old API still works:
471
+
472
+ ```typescript
473
+ import { Runflow } from '@runflow-ai/sdk/core';
474
+
475
+ Runflow.identify({
476
+ type: 'email',
477
+ value: 'user@example.com',
478
+ });
479
+ ```
480
+
441
481
  #### State Management
442
482
 
443
483
  ```typescript
@@ -1394,6 +1434,301 @@ The SDK supports various trace types:
1394
1434
  - `memory_operation` - Memory access
1395
1435
  - `connector_call` - Connector execution
1396
1436
  - `streaming_session` - Streaming response
1437
+ - `execution_summary` - Custom execution (new)
1438
+ - `custom_event` - Custom log event (new)
1439
+ - `error_event` - Error logging (new)
1440
+
1441
+ #### Custom Executions (Non-Agent Flows)
1442
+
1443
+ For scenarios without `agent.process()` (document analysis, batch processing, etc.):
1444
+
1445
+ ```typescript
1446
+ import { identify, startExecution, log } from '@runflow-ai/sdk/observability';
1447
+
1448
+ export async function analyzeDocument(docId: string) {
1449
+ // 1. Identify context
1450
+ identify({ type: 'document', value: docId });
1451
+
1452
+ // 2. Start custom execution
1453
+ const exec = startExecution({
1454
+ name: 'document-analysis',
1455
+ input: { documentId: docId }
1456
+ });
1457
+
1458
+ try {
1459
+ // 3. Process with LLM calls
1460
+ const llm = LLM.openai('gpt-4o');
1461
+
1462
+ const text = await llm.chat("Extract text from document...");
1463
+ exec.log('text_extracted', { length: text.length });
1464
+
1465
+ const category = await llm.chat(`Classify this: ${text}`);
1466
+ exec.log('document_classified', { category });
1467
+
1468
+ const summary = await llm.chat(`Summarize: ${text}`);
1469
+
1470
+ // 4. Finish with custom output
1471
+ await exec.end({
1472
+ output: {
1473
+ summary,
1474
+ category,
1475
+ documentId: docId
1476
+ }
1477
+ });
1478
+
1479
+ return { summary, category };
1480
+
1481
+ } catch (error) {
1482
+ exec.setError(error);
1483
+ await exec.end();
1484
+ throw error;
1485
+ }
1486
+ }
1487
+ ```
1488
+
1489
+ **In the Portal:**
1490
+ ```
1491
+ Thread: document_xxx_doc_456
1492
+ └─ Execution: "document-analysis"
1493
+ ├─ llm_call: Extract text
1494
+ ├─ custom_event: text_extracted
1495
+ ├─ llm_call: Classify
1496
+ ├─ custom_event: document_classified
1497
+ └─ llm_call: Summarize
1498
+ ```
1499
+
1500
+ #### Custom Logging
1501
+
1502
+ Log custom events within any execution:
1503
+
1504
+ ```typescript
1505
+ import { log, logEvent, logError } from '@runflow-ai/sdk/observability';
1506
+
1507
+ // Simple log
1508
+ log('cache_hit', { key: 'user_123' });
1509
+
1510
+ // Structured log
1511
+ logEvent('validation', {
1512
+ input: { orderId: '123', amount: 100 },
1513
+ output: { valid: true, score: 0.95 },
1514
+ metadata: { rule: 'fraud_detection' }
1515
+ });
1516
+
1517
+ // Error log
1518
+ try {
1519
+ await riskyOperation();
1520
+ } catch (error) {
1521
+ logError('operation_failed', error);
1522
+ throw error;
1523
+ }
1524
+ ```
1525
+
1526
+ Logs are automatically associated with the current execution and flushed with other traces.
1527
+
1528
+ #### Exception Safety
1529
+
1530
+ The SDK ensures traces are not lost even on crashes:
1531
+
1532
+ - **Exit handlers**: Auto-flush on `process.exit()`, `SIGTERM`, `SIGINT`
1533
+ - **Exception handlers**: Flush on `uncaughtException` and `unhandledRejection`
1534
+ - **Auto-cleanup**: Custom executions auto-flush after 60s if not manually ended
1535
+ - **Worker safety**: Execution engine waits 100ms for pending flushes
1536
+
1537
+ **Coverage: ~95% trace recovery** even on crashes.
1538
+
1539
+ #### Verbose Tracing Mode
1540
+
1541
+ **New in v2.1:** Control how much data is saved in traces - from minimal metadata to complete prompts and responses.
1542
+
1543
+ **Modes:**
1544
+ - **`minimal`**: Only essential metadata (production, minimal storage)
1545
+ - **`standard`**: Balanced metadata + sizes (default)
1546
+ - **`full`**: Complete data including prompts and responses (debugging)
1547
+
1548
+ **Simple API (string preset):**
1549
+ ```typescript
1550
+ const agent = new Agent({
1551
+ name: 'My Agent',
1552
+ model: openai('gpt-4o'),
1553
+ observability: 'full' // 'minimal', 'standard', or 'full'
1554
+ });
1555
+ ```
1556
+
1557
+ **Granular Control (object config):**
1558
+ ```typescript
1559
+ const agent = new Agent({
1560
+ name: 'My Agent',
1561
+ model: openai('gpt-4o'),
1562
+ observability: {
1563
+ mode: 'standard', // Base mode
1564
+ verboseLLM: true, // Override: save complete prompts
1565
+ verboseMemory: false, // Override: keep memory minimal
1566
+ verboseTools: true, // Override: save tool data (default)
1567
+ maxInputLength: 5000, // Truncate large inputs
1568
+ maxOutputLength: 5000, // Truncate large outputs
1569
+ }
1570
+ });
1571
+ ```
1572
+
1573
+ **Environment Variable:**
1574
+ ```bash
1575
+ # .env
1576
+ RUNFLOW_VERBOSE_TRACING=true # Auto-sets mode to 'full'
1577
+ ```
1578
+
1579
+ ```typescript
1580
+ // Auto-detects from environment
1581
+ const agent = new Agent({
1582
+ name: 'My Agent',
1583
+ model: openai('gpt-4o'),
1584
+ // observability: 'full' auto-applied if env var set
1585
+ });
1586
+ ```
1587
+
1588
+ **What Each Mode Saves:**
1589
+
1590
+ | Trace Type | Minimal | Standard | Full |
1591
+ |------------|---------|----------|------|
1592
+ | **LLM Call** | messagesCount, config | messagesCount, config | Complete messages + responses |
1593
+ | **Memory Load** | messagesCount | messagesCount | First 10 messages (truncated) |
1594
+ | **Memory Save** | messagesSaved | messagesSaved | User + assistant messages |
1595
+ | **Tool Call** | Always full (with truncation) | Always full | Always full |
1596
+ | **Agent Execution** | Always full | Always full | Always full |
1597
+
1598
+ **Storage Impact:**
1599
+
1600
+ - **Minimal**: ~100 bytes/trace
1601
+ - **Standard**: ~500 bytes/trace
1602
+ - **Full**: ~5KB/trace (with truncation)
1603
+
1604
+ **Recommended Usage:**
1605
+
1606
+ ```typescript
1607
+ // Production: minimal storage
1608
+ const prodAgent = new Agent({
1609
+ observability: 'minimal'
1610
+ });
1611
+
1612
+ // Staging: balanced
1613
+ const stagingAgent = new Agent({
1614
+ observability: 'standard'
1615
+ });
1616
+
1617
+ // Development: complete debugging
1618
+ const devAgent = new Agent({
1619
+ observability: 'full'
1620
+ });
1621
+
1622
+ // Or detect automatically
1623
+ const agent = new Agent({
1624
+ observability: process.env.NODE_ENV === 'production' ? 'minimal' : 'full'
1625
+ });
1626
+ ```
1627
+
1628
+ #### Trace Interceptor (onTrace)
1629
+
1630
+ Intercept and modify traces before they are sent, useful for:
1631
+ - Sending to external tools (DataDog, Sentry, CloudWatch)
1632
+ - Adding custom metadata
1633
+ - Filtering specific traces
1634
+ - Audit logging
1635
+
1636
+ **Example: Send to DataDog**
1637
+ ```typescript
1638
+ const agent = new Agent({
1639
+ observability: {
1640
+ mode: 'full',
1641
+ onTrace: (trace) => {
1642
+ // Send to DataDog
1643
+ datadogTracer.trace({
1644
+ name: trace.operation,
1645
+ resource: trace.type,
1646
+ duration: trace.duration,
1647
+ meta: trace.metadata
1648
+ });
1649
+
1650
+ // Return trace unchanged to continue normal flow
1651
+ return trace;
1652
+ }
1653
+ }
1654
+ });
1655
+ ```
1656
+
1657
+ **Example: Add Custom Metadata**
1658
+ ```typescript
1659
+ const agent = new Agent({
1660
+ observability: {
1661
+ onTrace: (trace) => {
1662
+ // Enrich with custom data
1663
+ trace.metadata.environment = 'production';
1664
+ trace.metadata.version = '1.0.0';
1665
+ trace.metadata.region = 'us-east-1';
1666
+
1667
+ return trace;
1668
+ }
1669
+ }
1670
+ });
1671
+ ```
1672
+
1673
+ **Example: Filter LLM Calls**
1674
+ ```typescript
1675
+ const agent = new Agent({
1676
+ observability: {
1677
+ onTrace: (trace) => {
1678
+ // Only send LLM calls to external tracker
1679
+ if (trace.type === 'llm_call') {
1680
+ externalTracker.send(trace);
1681
+ }
1682
+
1683
+ return trace;
1684
+ }
1685
+ }
1686
+ });
1687
+ ```
1688
+
1689
+ **Example: Cancel Sensitive Traces**
1690
+ ```typescript
1691
+ const agent = new Agent({
1692
+ observability: {
1693
+ onTrace: (trace) => {
1694
+ // Cancel traces with sensitive data
1695
+ if (trace.metadata?.containsSensitiveData) {
1696
+ return null; // ← Cancel trace (won't be sent)
1697
+ }
1698
+
1699
+ return trace;
1700
+ }
1701
+ }
1702
+ });
1703
+ ```
1704
+
1705
+ **Example: Error Tracking with Sentry**
1706
+ ```typescript
1707
+ const agent = new Agent({
1708
+ observability: {
1709
+ onTrace: (trace) => {
1710
+ // Send errors to Sentry
1711
+ if (trace.type === 'error_event' || trace.status === 'error') {
1712
+ Sentry.captureException(new Error(trace.error || 'Unknown error'), {
1713
+ extra: {
1714
+ traceId: trace.traceId,
1715
+ executionId: trace.executionId,
1716
+ operation: trace.operation,
1717
+ metadata: trace.metadata
1718
+ }
1719
+ });
1720
+ }
1721
+
1722
+ return trace;
1723
+ }
1724
+ }
1725
+ });
1726
+ ```
1727
+
1728
+ **Callback Return Values:**
1729
+ - `TraceData`: Modified trace (will be sent with changes)
1730
+ - `null`: Cancel trace (won't be sent or saved)
1731
+ - `void/undefined`: Continue with original trace
1397
1732
 
1398
1733
  ---
1399
1734
 
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/core/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAsBpG,qBAAa,KAAK;IAChB,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,SAAS,CAAC,CAAmB;IACrC,OAAO,CAAC,cAAc,CAAC,CAAM;IAC7B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,kBAAkB,CAAC,CAAS;IACpC,OAAO,CAAC,g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ACH,OAAO,CAAC,eAAe;IAqBvB,OAAO,CAAC,qBAAqB;IAI7B,OAAO,CAAC,mBAAmB;IAK3B,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,IAAI,YAAY,IAAI,MAAM,CAEzB;IAED,IAAI,KAAK,qCAER;IAED,IAAI,KAAK,mDAER;IAED,IAAI,YAAY,IAAI,OAAO,CAE1B;IAGK,aAAa,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,aAAa,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAyI5H"}
@@ -10,11 +10,16 @@ const agent_memory_1 = require("./helpers/agent-memory");
10
10
  const agent_rag_1 = require("./helpers/agent-rag");
11
11
  const agent_context_1 = require("./helpers/agent-context");
12
12
  const agent_utils_1 = require("./helpers/agent-utils");
13
+ const observability_helpers_1 = require("./helpers/observability-helpers");
13
14
  // ============================================================================
14
15
  // AGENT CLASS
15
16
  // ============================================================================
16
17
  class Agent {
17
18
  constructor(config) {
19
+ // Merge environment observability config
20
+ if (!config.observability && process.env.RUNFLOW_VERBOSE_TRACING === 'true') {
21
+ config.observability = 'full';
22
+ }
18
23
  this.config = config;
19
24
  // Configurar logger
20
25
  this.logger = (0, logger_1.createLogger)({
@@ -54,10 +59,14 @@ class Agent {
54
59
  this.apiClient = (0, api_client_1.createRunflowAPIClient)();
55
60
  // Use agentId from environment or config name as fallback
56
61
  const projectId = process.env.RUNFLOW_AGENT_ID || this.config.name.toLowerCase().replace(/\s+/g, '-');
62
+ // Get onTrace callback from observability config
63
+ const onTraceCallback = typeof this.config.observability === 'object'
64
+ ? this.config.observability.onTrace
65
+ : undefined;
57
66
  this.traceCollector = (0, trace_collector_1.createTraceCollector)(this.apiClient, projectId, {
58
67
  batchSize: 1, // Flush imediatamente após cada trace
59
68
  flushInterval: 1000,
60
- });
69
+ }, onTraceCallback);
61
70
  }
62
71
  }
63
72
  // Injetar API client (feito pela execution engine)
@@ -65,10 +74,16 @@ class Agent {
65
74
  const projectId = process.env.RUNFLOW_AGENT_ID || this.config.name.toLowerCase().replace(/\s+/g, '-');
66
75
  this.logger.debug('Setting API client', { projectId });
67
76
  this.apiClient = apiClient;
77
+ // Get onTrace callback from observability config
78
+ const onTraceCallback = typeof this.config.observability === 'object'
79
+ ? this.config.observability.onTrace
80
+ : undefined;
68
81
  this.traceCollector = (0, trace_collector_1.createTraceCollector)(apiClient, projectId, {
69
82
  batchSize: 1, // Flush imediatamente após cada trace
70
83
  flushInterval: 1000,
71
- });
84
+ }, onTraceCallback);
85
+ // Store in global for standalone functions
86
+ global.__runflowTraceCollector = this.traceCollector;
72
87
  }
73
88
  // Geração simples (aceita string ou array de messages)
74
89
  async generate(input) {
@@ -184,8 +199,14 @@ class Agent {
184
199
  if (llmSpan) {
185
200
  this.currentLLMSpanId = llmSpan.traceId;
186
201
  }
187
- // 🔍 Input do trace
188
- const llmInput = {
202
+ // 🔍 Input do trace (verbose ou resumido)
203
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(this.config.observability);
204
+ const verboseLLM = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, 'llm');
205
+ const llmInput = verboseLLM ? {
206
+ messages: (0, observability_helpers_1.truncateMessages)(messages, obsConfig.maxInputLength),
207
+ temperature: this.config.modelConfig?.temperature,
208
+ maxTokens: this.config.modelConfig?.maxTokens,
209
+ } : {
189
210
  messagesCount: messages.length,
190
211
  temperature: this.config.modelConfig?.temperature,
191
212
  maxTokens: this.config.modelConfig?.maxTokens,
@@ -221,8 +242,13 @@ class Agent {
221
242
  toolCallsCount: response.toolCalls?.length || 0,
222
243
  usage: response.usage
223
244
  });
224
- // 🔍 Output do trace
225
- const llmOutput = {
245
+ // 🔍 Output do trace (verbose ou resumido)
246
+ const llmOutput = verboseLLM ? {
247
+ text: (0, observability_helpers_1.truncateData)(response.text, obsConfig.maxOutputLength),
248
+ hasToolCalls: !!response.toolCalls && response.toolCalls.length > 0,
249
+ toolCallsCount: response.toolCalls?.length || 0,
250
+ toolCalls: response.toolCalls,
251
+ } : {
226
252
  responseLength: response.text?.length || 0,
227
253
  hasToolCalls: !!response.toolCalls && response.toolCalls.length > 0,
228
254
  toolCallsCount: response.toolCalls?.length || 0,
@@ -293,9 +319,12 @@ class Agent {
293
319
  });
294
320
  continue;
295
321
  }
322
+ // 🔍 Detectar se é RAG tool e usar span type específico
323
+ const isRAGTool = tool._isRAGTool === true;
324
+ const spanType = isRAGTool ? 'knowledge_search' : 'tool_call';
296
325
  // 🔍 Iniciar trace da tool execution (ANTES do try/catch, child of current LLM call)
297
326
  const toolStartTime = Date.now();
298
- const toolSpan = this.traceCollector?.startSpan('tool_call', {
327
+ const toolSpan = this.traceCollector?.startSpan(spanType, {
299
328
  toolName,
300
329
  toolId: tool.id,
301
330
  operation: 'execute',
@@ -307,8 +336,25 @@ class Agent {
307
336
  if (typeof args === 'string') {
308
337
  args = JSON.parse(args);
309
338
  }
310
- // 🔍 Input sempre vai completo para o trace
311
- toolSpan?.setInput(args);
339
+ // 🔍 Input do trace (com truncation para dados muito grandes)
340
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(this.config.observability);
341
+ const verboseMode = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, isRAGTool ? 'rag' : 'tool');
342
+ // 🔍 Para RAG tools, incluir parâmetros completos no trace
343
+ let traceInput;
344
+ if (isRAGTool) {
345
+ traceInput = {
346
+ query: args.query,
347
+ vectorStore: tool._vectorStore || 'unknown',
348
+ k: tool._k || 5,
349
+ threshold: tool._threshold || 0.7,
350
+ };
351
+ }
352
+ else {
353
+ traceInput = args;
354
+ }
355
+ toolSpan?.setInput(verboseMode
356
+ ? (0, observability_helpers_1.truncateData)(traceInput, obsConfig.maxInputLength)
357
+ : traceInput);
312
358
  // Executar tool com performance tracking
313
359
  // Note: Tools should use createRunflowAPIClient() singleton for API access
314
360
  const state = context_1.Runflow.getState();
@@ -320,7 +366,7 @@ class Agent {
320
366
  sessionId: state.sessionId,
321
367
  });
322
368
  }, { toolId: tool.id, iteration });
323
- // 🔍 Output sempre vai completo para o trace
369
+ // 🔍 Output do trace (com truncation para dados muito grandes)
324
370
  const toolEndTime = Date.now();
325
371
  const processingTimeMs = toolEndTime - toolStartTime;
326
372
  this.logger.info('Tool execution completed', {
@@ -329,7 +375,9 @@ class Agent {
329
375
  processingTimeMs,
330
376
  iteration
331
377
  });
332
- toolSpan?.setOutput(toolResult);
378
+ toolSpan?.setOutput(verboseMode
379
+ ? (0, observability_helpers_1.truncateData)(toolResult, obsConfig.maxOutputLength)
380
+ : toolResult);
333
381
  toolSpan?.setMetadata({
334
382
  toolName,
335
383
  toolId: tool.id,
@@ -523,8 +571,11 @@ class Agent {
523
571
  memoryId,
524
572
  memoryType: this.config.memory.type
525
573
  });
574
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(this.config.observability);
575
+ const verboseMemory = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, 'memory');
526
576
  const memoryLoadTime = await performance_logger_1.performanceLogger.measure('memory.load', async () => {
527
- return await (0, agent_memory_1.loadMemory)(memoryId, this.apiClient, this.config.memory, this.traceCollector, this.logger, this.currentAgentSpanId // Pass parent for hierarchy
577
+ return await (0, agent_memory_1.loadMemory)(memoryId, this.apiClient, this.config.memory, this.traceCollector, this.logger, this.currentAgentSpanId, // Pass parent for hierarchy
578
+ verboseMemory // Pass verbose flag
528
579
  );
529
580
  }, { memoryId, memoryType: this.config.memory.type });
530
581
  memoryMessages = memoryLoadTime;
@@ -565,8 +616,11 @@ class Agent {
565
616
  let memorySaveTime = 0;
566
617
  if (this.config.memory && memoryId) {
567
618
  this.logger.debug('Saving to memory', { memoryId });
619
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(this.config.observability);
620
+ const verboseMemory = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, 'memory');
568
621
  await performance_logger_1.performanceLogger.measure('memory.save', async () => {
569
- await (0, agent_memory_1.saveToMemory)(memoryId, input.message, result.text, this.apiClient, this.config.memory, this.config.model, this.traceCollector, this.logger, this.currentAgentSpanId // Pass parent for hierarchy
622
+ await (0, agent_memory_1.saveToMemory)(memoryId, input.message, result.text, this.apiClient, this.config.memory, this.config.model, this.traceCollector, this.logger, this.currentAgentSpanId, // Pass parent for hierarchy
623
+ verboseMemory // Pass verbose flag
570
624
  );
571
625
  }, { memoryId });
572
626
  memorySaveTime = Date.now() - processStartTime - llmProcessingTime;
@@ -757,7 +811,10 @@ Which agent should handle this? Respond with just the agent name.
757
811
  let memoryMessages = [];
758
812
  if (this.config.memory && memoryId) {
759
813
  this.logger.debug('Loading memory for streaming', { memoryId });
760
- memoryMessages = await (0, agent_memory_1.loadMemory)(memoryId, this.apiClient, this.config.memory, this.traceCollector, this.logger, this.currentAgentSpanId // Pass parent for hierarchy
814
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(this.config.observability);
815
+ const verboseMemory = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, 'memory');
816
+ memoryMessages = await (0, agent_memory_1.loadMemory)(memoryId, this.apiClient, this.config.memory, this.traceCollector, this.logger, this.currentAgentSpanId, // Pass parent for hierarchy
817
+ verboseMemory // Pass verbose flag
761
818
  );
762
819
  }
763
820
  // ============================================================================
@@ -798,6 +855,7 @@ Which agent should handle this? Respond with just the agent name.
798
855
  const modelConfig = this.config.model;
799
856
  const traceCollector = this.traceCollector;
800
857
  const agentSpanId = this.currentAgentSpanId;
858
+ const observabilityConfig = this.config.observability;
801
859
  return (async function* () {
802
860
  let fullResponse = '';
803
861
  for await (const chunk of stream) {
@@ -809,7 +867,10 @@ Which agent should handle this? Respond with just the agent name.
809
867
  // Salvar na memória quando streaming terminar
810
868
  if (memoryConfig && memoryId && apiClient) {
811
869
  logger.debug('Saving stream response to memory', { memoryId });
812
- await (0, agent_memory_1.saveToMemory)(memoryId, input.message, fullResponse, apiClient, memoryConfig, modelConfig, traceCollector, logger, agentSpanId // Pass parent for hierarchy
870
+ const obsConfig = (0, observability_helpers_1.normalizeObservabilityConfig)(observabilityConfig);
871
+ const verboseMemory = (0, observability_helpers_1.shouldUseVerbose)(obsConfig, 'memory');
872
+ await (0, agent_memory_1.saveToMemory)(memoryId, input.message, fullResponse, apiClient, memoryConfig, modelConfig, traceCollector, logger, agentSpanId, // Pass parent for hierarchy
873
+ verboseMemory // Pass verbose flag
813
874
  );
814
875
  }
815
876
  logger.info('Stream processing completed', {