@cogitator-ai/workflows 0.1.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.
Files changed (179) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -0
  3. package/dist/builder.d.ts +39 -0
  4. package/dist/builder.d.ts.map +1 -0
  5. package/dist/builder.js +224 -0
  6. package/dist/builder.js.map +1 -0
  7. package/dist/checkpoint.d.ts +33 -0
  8. package/dist/checkpoint.d.ts.map +1 -0
  9. package/dist/checkpoint.js +108 -0
  10. package/dist/checkpoint.js.map +1 -0
  11. package/dist/executor.d.ts +24 -0
  12. package/dist/executor.d.ts.map +1 -0
  13. package/dist/executor.js +207 -0
  14. package/dist/executor.js.map +1 -0
  15. package/dist/human/approval-store.d.ts +95 -0
  16. package/dist/human/approval-store.d.ts.map +1 -0
  17. package/dist/human/approval-store.js +377 -0
  18. package/dist/human/approval-store.js.map +1 -0
  19. package/dist/human/human-node.d.ts +104 -0
  20. package/dist/human/human-node.d.ts.map +1 -0
  21. package/dist/human/human-node.js +342 -0
  22. package/dist/human/human-node.js.map +1 -0
  23. package/dist/human/index.d.ts +17 -0
  24. package/dist/human/index.d.ts.map +1 -0
  25. package/dist/human/index.js +17 -0
  26. package/dist/human/index.js.map +1 -0
  27. package/dist/human/notifiers.d.ts +85 -0
  28. package/dist/human/notifiers.d.ts.map +1 -0
  29. package/dist/human/notifiers.js +289 -0
  30. package/dist/human/notifiers.js.map +1 -0
  31. package/dist/index.d.ts +32 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +19 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/manager/index.d.ts +19 -0
  36. package/dist/manager/index.d.ts.map +1 -0
  37. package/dist/manager/index.js +17 -0
  38. package/dist/manager/index.js.map +1 -0
  39. package/dist/manager/run-store.d.ts +78 -0
  40. package/dist/manager/run-store.d.ts.map +1 -0
  41. package/dist/manager/run-store.js +390 -0
  42. package/dist/manager/run-store.js.map +1 -0
  43. package/dist/manager/scheduler.d.ts +159 -0
  44. package/dist/manager/scheduler.d.ts.map +1 -0
  45. package/dist/manager/scheduler.js +355 -0
  46. package/dist/manager/scheduler.js.map +1 -0
  47. package/dist/manager/workflow-manager.d.ts +114 -0
  48. package/dist/manager/workflow-manager.d.ts.map +1 -0
  49. package/dist/manager/workflow-manager.js +460 -0
  50. package/dist/manager/workflow-manager.js.map +1 -0
  51. package/dist/nodes/agent.d.ts +24 -0
  52. package/dist/nodes/agent.d.ts.map +1 -0
  53. package/dist/nodes/agent.js +37 -0
  54. package/dist/nodes/agent.js.map +1 -0
  55. package/dist/nodes/base.d.ts +12 -0
  56. package/dist/nodes/base.d.ts.map +1 -0
  57. package/dist/nodes/base.js +5 -0
  58. package/dist/nodes/base.js.map +1 -0
  59. package/dist/nodes/function.d.ts +27 -0
  60. package/dist/nodes/function.d.ts.map +1 -0
  61. package/dist/nodes/function.js +29 -0
  62. package/dist/nodes/function.js.map +1 -0
  63. package/dist/nodes/index.d.ts +8 -0
  64. package/dist/nodes/index.d.ts.map +1 -0
  65. package/dist/nodes/index.js +8 -0
  66. package/dist/nodes/index.js.map +1 -0
  67. package/dist/nodes/tool.d.ts +19 -0
  68. package/dist/nodes/tool.d.ts.map +1 -0
  69. package/dist/nodes/tool.js +26 -0
  70. package/dist/nodes/tool.js.map +1 -0
  71. package/dist/observability/exporters.d.ts +93 -0
  72. package/dist/observability/exporters.d.ts.map +1 -0
  73. package/dist/observability/exporters.js +330 -0
  74. package/dist/observability/exporters.js.map +1 -0
  75. package/dist/observability/index.d.ts +17 -0
  76. package/dist/observability/index.d.ts.map +1 -0
  77. package/dist/observability/index.js +17 -0
  78. package/dist/observability/index.js.map +1 -0
  79. package/dist/observability/metrics.d.ts +114 -0
  80. package/dist/observability/metrics.d.ts.map +1 -0
  81. package/dist/observability/metrics.js +435 -0
  82. package/dist/observability/metrics.js.map +1 -0
  83. package/dist/observability/span-attributes.d.ts +95 -0
  84. package/dist/observability/span-attributes.d.ts.map +1 -0
  85. package/dist/observability/span-attributes.js +142 -0
  86. package/dist/observability/span-attributes.js.map +1 -0
  87. package/dist/observability/tracer.d.ts +110 -0
  88. package/dist/observability/tracer.d.ts.map +1 -0
  89. package/dist/observability/tracer.js +409 -0
  90. package/dist/observability/tracer.js.map +1 -0
  91. package/dist/patterns/index.d.ts +15 -0
  92. package/dist/patterns/index.d.ts.map +1 -0
  93. package/dist/patterns/index.js +15 -0
  94. package/dist/patterns/index.js.map +1 -0
  95. package/dist/patterns/map-reduce.d.ts +223 -0
  96. package/dist/patterns/map-reduce.d.ts.map +1 -0
  97. package/dist/patterns/map-reduce.js +378 -0
  98. package/dist/patterns/map-reduce.js.map +1 -0
  99. package/dist/saga/circuit-breaker.d.ts +153 -0
  100. package/dist/saga/circuit-breaker.d.ts.map +1 -0
  101. package/dist/saga/circuit-breaker.js +306 -0
  102. package/dist/saga/circuit-breaker.js.map +1 -0
  103. package/dist/saga/compensation.d.ts +134 -0
  104. package/dist/saga/compensation.d.ts.map +1 -0
  105. package/dist/saga/compensation.js +240 -0
  106. package/dist/saga/compensation.js.map +1 -0
  107. package/dist/saga/dead-letter.d.ts +113 -0
  108. package/dist/saga/dead-letter.d.ts.map +1 -0
  109. package/dist/saga/dead-letter.js +307 -0
  110. package/dist/saga/dead-letter.js.map +1 -0
  111. package/dist/saga/idempotency.d.ts +95 -0
  112. package/dist/saga/idempotency.d.ts.map +1 -0
  113. package/dist/saga/idempotency.js +266 -0
  114. package/dist/saga/idempotency.js.map +1 -0
  115. package/dist/saga/index.d.ts +16 -0
  116. package/dist/saga/index.d.ts.map +1 -0
  117. package/dist/saga/index.js +16 -0
  118. package/dist/saga/index.js.map +1 -0
  119. package/dist/saga/retry.d.ts +59 -0
  120. package/dist/saga/retry.d.ts.map +1 -0
  121. package/dist/saga/retry.js +222 -0
  122. package/dist/saga/retry.js.map +1 -0
  123. package/dist/scheduler.d.ts +37 -0
  124. package/dist/scheduler.d.ts.map +1 -0
  125. package/dist/scheduler.js +151 -0
  126. package/dist/scheduler.js.map +1 -0
  127. package/dist/subworkflows/index.d.ts +16 -0
  128. package/dist/subworkflows/index.d.ts.map +1 -0
  129. package/dist/subworkflows/index.js +16 -0
  130. package/dist/subworkflows/index.js.map +1 -0
  131. package/dist/subworkflows/parallel-subworkflows.d.ts +139 -0
  132. package/dist/subworkflows/parallel-subworkflows.d.ts.map +1 -0
  133. package/dist/subworkflows/parallel-subworkflows.js +270 -0
  134. package/dist/subworkflows/parallel-subworkflows.js.map +1 -0
  135. package/dist/subworkflows/subworkflow-node.d.ts +136 -0
  136. package/dist/subworkflows/subworkflow-node.d.ts.map +1 -0
  137. package/dist/subworkflows/subworkflow-node.js +164 -0
  138. package/dist/subworkflows/subworkflow-node.js.map +1 -0
  139. package/dist/timers/cron-parser.d.ts +110 -0
  140. package/dist/timers/cron-parser.d.ts.map +1 -0
  141. package/dist/timers/cron-parser.js +412 -0
  142. package/dist/timers/cron-parser.js.map +1 -0
  143. package/dist/timers/index.d.ts +18 -0
  144. package/dist/timers/index.d.ts.map +1 -0
  145. package/dist/timers/index.js +18 -0
  146. package/dist/timers/index.js.map +1 -0
  147. package/dist/timers/timer-manager.d.ts +219 -0
  148. package/dist/timers/timer-manager.d.ts.map +1 -0
  149. package/dist/timers/timer-manager.js +351 -0
  150. package/dist/timers/timer-manager.js.map +1 -0
  151. package/dist/timers/timer-node.d.ts +144 -0
  152. package/dist/timers/timer-node.d.ts.map +1 -0
  153. package/dist/timers/timer-node.js +246 -0
  154. package/dist/timers/timer-node.js.map +1 -0
  155. package/dist/timers/timer-store.d.ts +90 -0
  156. package/dist/timers/timer-store.d.ts.map +1 -0
  157. package/dist/timers/timer-store.js +357 -0
  158. package/dist/timers/timer-store.js.map +1 -0
  159. package/dist/triggers/cron-trigger.d.ts +102 -0
  160. package/dist/triggers/cron-trigger.d.ts.map +1 -0
  161. package/dist/triggers/cron-trigger.js +309 -0
  162. package/dist/triggers/cron-trigger.js.map +1 -0
  163. package/dist/triggers/index.d.ts +14 -0
  164. package/dist/triggers/index.d.ts.map +1 -0
  165. package/dist/triggers/index.js +10 -0
  166. package/dist/triggers/index.js.map +1 -0
  167. package/dist/triggers/rate-limiter.d.ts +130 -0
  168. package/dist/triggers/rate-limiter.d.ts.map +1 -0
  169. package/dist/triggers/rate-limiter.js +294 -0
  170. package/dist/triggers/rate-limiter.js.map +1 -0
  171. package/dist/triggers/trigger-manager.d.ts +166 -0
  172. package/dist/triggers/trigger-manager.d.ts.map +1 -0
  173. package/dist/triggers/trigger-manager.js +436 -0
  174. package/dist/triggers/trigger-manager.js.map +1 -0
  175. package/dist/triggers/webhook-trigger.d.ts +150 -0
  176. package/dist/triggers/webhook-trigger.d.ts.map +1 -0
  177. package/dist/triggers/webhook-trigger.js +452 -0
  178. package/dist/triggers/webhook-trigger.js.map +1 -0
  179. package/package.json +44 -0
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Standard span attributes for workflow tracing
3
+ * Based on OpenTelemetry semantic conventions + custom workflow attributes
4
+ */
5
+ export const TRACE_PARENT_HEADER = 'traceparent';
6
+ export const TRACE_STATE_HEADER = 'tracestate';
7
+ export const BAGGAGE_HEADER = 'baggage';
8
+ export const SERVICE_NAME = 'service.name';
9
+ export const SERVICE_VERSION = 'service.version';
10
+ export const SERVICE_INSTANCE_ID = 'service.instance.id';
11
+ export const WORKFLOW_NAME = 'workflow.name';
12
+ export const WORKFLOW_ID = 'workflow.id';
13
+ export const WORKFLOW_RUN_ID = 'workflow.run.id';
14
+ export const WORKFLOW_VERSION = 'workflow.version';
15
+ export const WORKFLOW_ENTRY_POINT = 'workflow.entry_point';
16
+ export const WORKFLOW_NODE_COUNT = 'workflow.node_count';
17
+ export const WORKFLOW_STATUS = 'workflow.status';
18
+ export const NODE_NAME = 'node.name';
19
+ export const NODE_TYPE = 'node.type';
20
+ export const NODE_INDEX = 'node.index';
21
+ export const NODE_RETRY_COUNT = 'node.retry_count';
22
+ export const NODE_TIMEOUT = 'node.timeout';
23
+ export const NODE_DURATION = 'node.duration_ms';
24
+ export const NODE_STATUS = 'node.status';
25
+ export const LLM_SYSTEM = 'llm.system';
26
+ export const LLM_REQUEST_MODEL = 'llm.request.model';
27
+ export const LLM_RESPONSE_MODEL = 'llm.response.model';
28
+ export const LLM_REQUEST_MAX_TOKENS = 'llm.request.max_tokens';
29
+ export const LLM_REQUEST_TEMPERATURE = 'llm.request.temperature';
30
+ export const LLM_REQUEST_TOP_P = 'llm.request.top_p';
31
+ export const LLM_USAGE_INPUT_TOKENS = 'llm.usage.input_tokens';
32
+ export const LLM_USAGE_OUTPUT_TOKENS = 'llm.usage.output_tokens';
33
+ export const LLM_USAGE_TOTAL_TOKENS = 'llm.usage.total_tokens';
34
+ export const LLM_USAGE_COST = 'llm.usage.cost';
35
+ export const TOOL_NAME = 'tool.name';
36
+ export const TOOL_PARAMETERS = 'tool.parameters';
37
+ export const TOOL_RESULT = 'tool.result';
38
+ export const TOOL_DURATION = 'tool.duration_ms';
39
+ export const TOOL_SUCCESS = 'tool.success';
40
+ export const ERROR_TYPE = 'error.type';
41
+ export const ERROR_MESSAGE = 'error.message';
42
+ export const ERROR_STACK = 'error.stack';
43
+ export const ERROR_CODE = 'error.code';
44
+ export const RETRY_ATTEMPT = 'retry.attempt';
45
+ export const RETRY_MAX = 'retry.max';
46
+ export const RETRY_DELAY = 'retry.delay_ms';
47
+ export const CIRCUIT_BREAKER_STATE = 'circuit_breaker.state';
48
+ export const COMPENSATION_TRIGGERED = 'compensation.triggered';
49
+ export const COMPENSATION_NODE = 'compensation.node';
50
+ export const DEAD_LETTER_QUEUE = 'dlq.added';
51
+ export const APPROVAL_ID = 'approval.id';
52
+ export const APPROVAL_TYPE = 'approval.type';
53
+ export const APPROVAL_STATUS = 'approval.status';
54
+ export const APPROVAL_TIMEOUT = 'approval.timeout_ms';
55
+ export const APPROVAL_ASSIGNEE = 'approval.assignee';
56
+ export const TIMER_TYPE = 'timer.type';
57
+ export const TIMER_DELAY = 'timer.delay_ms';
58
+ export const TIMER_CRON = 'timer.cron';
59
+ export const TIMER_SCHEDULED_AT = 'timer.scheduled_at';
60
+ export const TIMER_FIRED_AT = 'timer.fired_at';
61
+ export const SUBWORKFLOW_NAME = 'subworkflow.name';
62
+ export const SUBWORKFLOW_DEPTH = 'subworkflow.depth';
63
+ export const SUBWORKFLOW_PARENT_ID = 'subworkflow.parent_id';
64
+ export const TRIGGER_TYPE = 'trigger.type';
65
+ export const TRIGGER_ID = 'trigger.id';
66
+ export const TRIGGER_SOURCE = 'trigger.source';
67
+ export const WEBHOOK_PATH = 'webhook.path';
68
+ export const WEBHOOK_METHOD = 'webhook.method';
69
+ export const CRON_EXPRESSION = 'cron.expression';
70
+ export const CRON_NEXT_RUN = 'cron.next_run';
71
+ /**
72
+ * Build standard workflow span attributes
73
+ */
74
+ export function workflowSpanAttributes(workflowName, workflowId, runId, additionalAttrs) {
75
+ return {
76
+ [WORKFLOW_NAME]: workflowName,
77
+ [WORKFLOW_ID]: workflowId,
78
+ [WORKFLOW_RUN_ID]: runId,
79
+ ...additionalAttrs,
80
+ };
81
+ }
82
+ /**
83
+ * Build standard node span attributes
84
+ */
85
+ export function nodeSpanAttributes(nodeName, nodeType, nodeIndex, additionalAttrs) {
86
+ return {
87
+ [NODE_NAME]: nodeName,
88
+ [NODE_TYPE]: nodeType,
89
+ [NODE_INDEX]: nodeIndex,
90
+ ...additionalAttrs,
91
+ };
92
+ }
93
+ /**
94
+ * Build LLM span attributes from token usage
95
+ */
96
+ export function llmSpanAttributes(system, model, inputTokens, outputTokens, cost, additionalAttrs) {
97
+ const attrs = {
98
+ [LLM_SYSTEM]: system,
99
+ [LLM_REQUEST_MODEL]: model,
100
+ [LLM_USAGE_INPUT_TOKENS]: inputTokens,
101
+ [LLM_USAGE_OUTPUT_TOKENS]: outputTokens,
102
+ [LLM_USAGE_TOTAL_TOKENS]: inputTokens + outputTokens,
103
+ };
104
+ if (cost !== undefined) {
105
+ attrs[LLM_USAGE_COST] = cost;
106
+ }
107
+ return { ...attrs, ...additionalAttrs };
108
+ }
109
+ /**
110
+ * Build tool span attributes
111
+ */
112
+ export function toolSpanAttributes(toolName, success, durationMs, additionalAttrs) {
113
+ return {
114
+ [TOOL_NAME]: toolName,
115
+ [TOOL_SUCCESS]: success,
116
+ [TOOL_DURATION]: durationMs,
117
+ ...additionalAttrs,
118
+ };
119
+ }
120
+ /**
121
+ * Build error span attributes
122
+ */
123
+ export function errorSpanAttributes(error, additionalAttrs) {
124
+ return {
125
+ [ERROR_TYPE]: error.name,
126
+ [ERROR_MESSAGE]: error.message,
127
+ [ERROR_STACK]: error.stack,
128
+ ...additionalAttrs,
129
+ };
130
+ }
131
+ /**
132
+ * Build retry span attributes
133
+ */
134
+ export function retrySpanAttributes(attempt, maxAttempts, delayMs, additionalAttrs) {
135
+ return {
136
+ [RETRY_ATTEMPT]: attempt,
137
+ [RETRY_MAX]: maxAttempts,
138
+ [RETRY_DELAY]: delayMs,
139
+ ...additionalAttrs,
140
+ };
141
+ }
142
+ //# sourceMappingURL=span-attributes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"span-attributes.js","sourceRoot":"","sources":["../../src/observability/span-attributes.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG,aAAa,CAAC;AACjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,YAAY,CAAC;AAC/C,MAAM,CAAC,MAAM,cAAc,GAAG,SAAS,CAAC;AAExC,MAAM,CAAC,MAAM,YAAY,GAAG,cAAc,CAAC;AAC3C,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AACjD,MAAM,CAAC,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAEzD,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC;AAC7C,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAC;AACzC,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AACjD,MAAM,CAAC,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,sBAAsB,CAAC,EAAE,WAAW,GAAG,YAAY;KACrD,CAAC;IAEF,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,KAAK,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IAC/B,CAAC;IAED,OAAO,EAAE,GAAG,KAAK,EAAE,GAAG,eAAe,EAAE,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAAgB,EAChB,OAAgB,EAChB,UAAkB,EAClB,eAAyC;IAEzC,OAAO;QACL,CAAC,SAAS,CAAC,EAAE,QAAQ;QACrB,CAAC,YAAY,CAAC,EAAE,OAAO;QACvB,CAAC,aAAa,CAAC,EAAE,UAAU;QAC3B,GAAG,eAAe;KACnB,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAAY,EACZ,eAAyC;IAEzC,OAAO;QACL,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC,IAAI;QACxB,CAAC,aAAa,CAAC,EAAE,KAAK,CAAC,OAAO;QAC9B,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC,KAAK;QAC1B,GAAG,eAAe;KACnB,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,OAAe,EACf,WAAmB,EACnB,OAAe,EACf,eAAyC;IAEzC,OAAO;QACL,CAAC,aAAa,CAAC,EAAE,OAAO;QACxB,CAAC,SAAS,CAAC,EAAE,WAAW;QACxB,CAAC,WAAW,CAAC,EAAE,OAAO;QACtB,GAAG,eAAe;KACnB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * WorkflowTracer - Distributed tracing for workflow execution
3
+ *
4
+ * Features:
5
+ * - W3C Trace Context propagation
6
+ * - Hierarchical span creation (workflow → node → tool)
7
+ * - Automatic span lifecycle management
8
+ * - Context-aware span attributes
9
+ * - Multi-backend export support
10
+ */
11
+ import type { TracingConfig, WorkflowSpan, SpanKind, SpanStatus, SpanLink, TraceContext } from '@cogitator-ai/types';
12
+ /**
13
+ * Active span context for scoped operations
14
+ */
15
+ interface SpanScope {
16
+ span: WorkflowSpan;
17
+ end: (status?: SpanStatus, message?: string) => void;
18
+ addEvent: (name: string, attributes?: Record<string, unknown>) => void;
19
+ setAttribute: (key: string, value: unknown) => void;
20
+ setAttributes: (attributes: Record<string, unknown>) => void;
21
+ recordException: (error: Error) => void;
22
+ }
23
+ /**
24
+ * WorkflowTracer - Main tracing class
25
+ */
26
+ export declare class WorkflowTracer {
27
+ private config;
28
+ private exporter;
29
+ private spanStack;
30
+ private completedSpans;
31
+ private currentTraceContext;
32
+ private baggage;
33
+ private sampleDecision;
34
+ constructor(config?: Partial<TracingConfig>);
35
+ /**
36
+ * Check if this tracer is sampling
37
+ */
38
+ isSampled(): boolean;
39
+ /**
40
+ * Set trace context from incoming request headers
41
+ */
42
+ setContextFromHeaders(headers: Record<string, string>): void;
43
+ /**
44
+ * Get headers for outgoing request context propagation
45
+ */
46
+ getContextHeaders(): Record<string, string>;
47
+ /**
48
+ * Set a baggage value
49
+ */
50
+ setBaggage(key: string, value: string): void;
51
+ /**
52
+ * Get a baggage value
53
+ */
54
+ getBaggage(key: string): string | undefined;
55
+ /**
56
+ * Get current trace context
57
+ */
58
+ getTraceContext(): TraceContext | null;
59
+ /**
60
+ * Start a new workflow trace
61
+ */
62
+ startWorkflowSpan(workflowName: string, workflowId: string, runId: string, attributes?: Record<string, unknown>): SpanScope;
63
+ /**
64
+ * Start a node execution span
65
+ */
66
+ startNodeSpan(nodeName: string, nodeType: string, attributes?: Record<string, unknown>): SpanScope;
67
+ /**
68
+ * Start a tool execution span
69
+ */
70
+ startToolSpan(toolName: string, attributes?: Record<string, unknown>): SpanScope;
71
+ /**
72
+ * Start a custom span
73
+ */
74
+ startSpan(name: string, kind?: SpanKind, attributes?: Record<string, unknown>): SpanScope;
75
+ /**
76
+ * Create a span scope with lifecycle methods
77
+ */
78
+ private createSpanScope;
79
+ /**
80
+ * Add a link between spans
81
+ */
82
+ addLink(span: WorkflowSpan, link: SpanLink): void;
83
+ /**
84
+ * Get current active span
85
+ */
86
+ getCurrentSpan(): WorkflowSpan | undefined;
87
+ /**
88
+ * Flush completed spans to exporter
89
+ */
90
+ flush(): Promise<void>;
91
+ /**
92
+ * Shutdown tracer and flush remaining spans
93
+ */
94
+ shutdown(): Promise<void>;
95
+ /**
96
+ * Run a function with automatic span creation
97
+ */
98
+ trace<T>(name: string, fn: (scope: SpanScope) => Promise<T>, options?: {
99
+ kind?: SpanKind;
100
+ attributes?: Record<string, unknown>;
101
+ }): Promise<T>;
102
+ }
103
+ /**
104
+ * Create a tracer instance
105
+ */
106
+ export declare function createTracer(config?: Partial<TracingConfig>): WorkflowTracer;
107
+ export declare function getGlobalTracer(): WorkflowTracer;
108
+ export declare function setGlobalTracer(tracer: WorkflowTracer): void;
109
+ export {};
110
+ //# sourceMappingURL=tracer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/observability/tracer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,YAAY,EAEb,MAAM,qBAAqB,CAAC;AAiG7B;;GAEG;AACH,UAAU,SAAS;IACjB,IAAI,EAAE,YAAY,CAAC;IACnB,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IACrD,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;IACvE,YAAY,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACpD,aAAa,EAAE,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAA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CAAC,GACnC,SAAS;IA0BZ;;OAEG;IACH,SAAS,CACP,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,QAAqB,EAC3B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACnC,SAAS;IAuBZ;;OAEG;IACH,OAAO,CAAC,eAAe;IA4DvB;;OAEG;IACH,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,QAAQ,GAAG,IAAI;IAIjD;;OAEG;IACH,cAAc,IAAI,YAAY,GAAG,SAAS;IAI1C;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAW5B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAK/B;;OAEG;IACG,KAAK,CAAC,CAAC,EACX,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,EACpC,OAAO,CAAC,EAAE;QACR,IAAI,CAAC,EAAE,QAAQ,CAAC;QAChB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACtC,GACA,OAAO,CAAC,CAAC,CAAC;CAad;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,cAAc,CAE5E;AAOD,wBAAgB,eAAe,IAAI,cAAc,CAKhD;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAE5D"}
@@ -0,0 +1,409 @@
1
+ /**
2
+ * WorkflowTracer - Distributed tracing for workflow execution
3
+ *
4
+ * Features:
5
+ * - W3C Trace Context propagation
6
+ * - Hierarchical span creation (workflow → node → tool)
7
+ * - Automatic span lifecycle management
8
+ * - Context-aware span attributes
9
+ * - Multi-backend export support
10
+ */
11
+ import { nanoid } from 'nanoid';
12
+ import { createSpanExporter, NoopSpanExporter, } from './exporters';
13
+ import { TRACE_PARENT_HEADER, TRACE_STATE_HEADER, BAGGAGE_HEADER, WORKFLOW_NAME, WORKFLOW_ID, WORKFLOW_RUN_ID, SERVICE_NAME, SERVICE_VERSION, } from './span-attributes';
14
+ const TRACE_VERSION = '00';
15
+ const DEFAULT_SAMPLE_RATE = 1.0;
16
+ /**
17
+ * Generate a random trace ID (32 hex chars)
18
+ */
19
+ function generateTraceId() {
20
+ return nanoid(16)
21
+ .split('')
22
+ .map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
23
+ .join('')
24
+ .slice(0, 32);
25
+ }
26
+ /**
27
+ * Generate a random span ID (16 hex chars)
28
+ */
29
+ function generateSpanId() {
30
+ return nanoid(8)
31
+ .split('')
32
+ .map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
33
+ .join('')
34
+ .slice(0, 16);
35
+ }
36
+ /**
37
+ * Parse W3C traceparent header
38
+ * Format: {version}-{trace-id}-{parent-id}-{trace-flags}
39
+ */
40
+ function parseTraceParent(header) {
41
+ const parts = header.split('-');
42
+ if (parts.length !== 4)
43
+ return null;
44
+ const [version, traceId, spanId, flags] = parts;
45
+ if (version !== TRACE_VERSION)
46
+ return null;
47
+ if (traceId.length !== 32 || spanId.length !== 16)
48
+ return null;
49
+ return {
50
+ traceId,
51
+ spanId,
52
+ traceFlags: parseInt(flags, 16),
53
+ };
54
+ }
55
+ /**
56
+ * Format TraceContext to W3C traceparent header
57
+ */
58
+ function formatTraceParent(ctx) {
59
+ const flags = (ctx.traceFlags ?? 1).toString(16).padStart(2, '0');
60
+ return `${TRACE_VERSION}-${ctx.traceId}-${ctx.spanId}-${flags}`;
61
+ }
62
+ /**
63
+ * Parse W3C baggage header
64
+ * Format: key1=value1,key2=value2
65
+ */
66
+ function parseBaggage(header) {
67
+ const baggage = {};
68
+ const pairs = header.split(',');
69
+ for (const pair of pairs) {
70
+ const [key, value] = pair.split('=');
71
+ if (key && value) {
72
+ baggage[key.trim()] = decodeURIComponent(value.trim());
73
+ }
74
+ }
75
+ return baggage;
76
+ }
77
+ /**
78
+ * Format Baggage to W3C baggage header
79
+ */
80
+ function formatBaggage(baggage) {
81
+ return Object.entries(baggage)
82
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
83
+ .join(',');
84
+ }
85
+ /**
86
+ * WorkflowTracer - Main tracing class
87
+ */
88
+ export class WorkflowTracer {
89
+ config;
90
+ exporter;
91
+ spanStack = [];
92
+ completedSpans = [];
93
+ currentTraceContext = null;
94
+ baggage = {};
95
+ sampleDecision = true;
96
+ constructor(config = {}) {
97
+ this.config = {
98
+ enabled: true,
99
+ serviceName: 'cogitator-workflow',
100
+ serviceVersion: '1.0.0',
101
+ sampleRate: DEFAULT_SAMPLE_RATE,
102
+ propagateContext: true,
103
+ exporter: 'console',
104
+ ...config,
105
+ };
106
+ if (!this.config.enabled) {
107
+ this.exporter = new NoopSpanExporter();
108
+ return;
109
+ }
110
+ this.exporter = createSpanExporter({
111
+ type: this.config.exporter ?? 'console',
112
+ endpoint: this.config.exporterEndpoint,
113
+ headers: this.config.exporterHeaders,
114
+ batchSize: this.config.batchSize,
115
+ flushInterval: this.config.flushInterval,
116
+ });
117
+ this.sampleDecision = Math.random() < (this.config.sampleRate ?? 1.0);
118
+ }
119
+ /**
120
+ * Check if this tracer is sampling
121
+ */
122
+ isSampled() {
123
+ return this.config.enabled && this.sampleDecision;
124
+ }
125
+ /**
126
+ * Set trace context from incoming request headers
127
+ */
128
+ setContextFromHeaders(headers) {
129
+ const traceparent = headers[TRACE_PARENT_HEADER];
130
+ if (traceparent) {
131
+ this.currentTraceContext = parseTraceParent(traceparent);
132
+ }
133
+ const tracestate = headers[TRACE_STATE_HEADER];
134
+ if (tracestate && this.currentTraceContext) {
135
+ this.currentTraceContext.traceState = tracestate;
136
+ }
137
+ const baggageHeader = headers[BAGGAGE_HEADER];
138
+ if (baggageHeader) {
139
+ this.baggage = { ...this.baggage, ...parseBaggage(baggageHeader) };
140
+ }
141
+ }
142
+ /**
143
+ * Get headers for outgoing request context propagation
144
+ */
145
+ getContextHeaders() {
146
+ const headers = {};
147
+ if (this.currentTraceContext && this.config.propagateContext) {
148
+ headers[TRACE_PARENT_HEADER] = formatTraceParent(this.currentTraceContext);
149
+ if (this.currentTraceContext.traceState) {
150
+ headers[TRACE_STATE_HEADER] = this.currentTraceContext.traceState;
151
+ }
152
+ }
153
+ if (Object.keys(this.baggage).length > 0) {
154
+ headers[BAGGAGE_HEADER] = formatBaggage(this.baggage);
155
+ }
156
+ return headers;
157
+ }
158
+ /**
159
+ * Set a baggage value
160
+ */
161
+ setBaggage(key, value) {
162
+ this.baggage[key] = value;
163
+ }
164
+ /**
165
+ * Get a baggage value
166
+ */
167
+ getBaggage(key) {
168
+ return this.baggage[key];
169
+ }
170
+ /**
171
+ * Get current trace context
172
+ */
173
+ getTraceContext() {
174
+ return this.currentTraceContext;
175
+ }
176
+ /**
177
+ * Start a new workflow trace
178
+ */
179
+ startWorkflowSpan(workflowName, workflowId, runId, attributes) {
180
+ const traceId = this.currentTraceContext?.traceId ?? generateTraceId();
181
+ const spanId = generateSpanId();
182
+ const parentSpanId = this.currentTraceContext?.spanId;
183
+ const span = {
184
+ traceId,
185
+ spanId,
186
+ parentSpanId,
187
+ name: `workflow:${workflowName}`,
188
+ kind: 'internal',
189
+ startTime: Date.now(),
190
+ attributes: {
191
+ [SERVICE_NAME]: this.config.serviceName,
192
+ [SERVICE_VERSION]: this.config.serviceVersion,
193
+ [WORKFLOW_NAME]: workflowName,
194
+ [WORKFLOW_ID]: workflowId,
195
+ [WORKFLOW_RUN_ID]: runId,
196
+ ...this.config.attributes,
197
+ ...attributes,
198
+ },
199
+ events: [],
200
+ links: [],
201
+ status: 'unset',
202
+ };
203
+ this.currentTraceContext = {
204
+ traceId,
205
+ spanId,
206
+ traceFlags: 1,
207
+ };
208
+ this.spanStack.push(span);
209
+ return this.createSpanScope(span);
210
+ }
211
+ /**
212
+ * Start a node execution span
213
+ */
214
+ startNodeSpan(nodeName, nodeType, attributes) {
215
+ const parentSpan = this.spanStack[this.spanStack.length - 1];
216
+ const traceId = parentSpan?.traceId ?? generateTraceId();
217
+ const spanId = generateSpanId();
218
+ const span = {
219
+ traceId,
220
+ spanId,
221
+ parentSpanId: parentSpan?.spanId,
222
+ name: `node:${nodeName}`,
223
+ kind: 'internal',
224
+ startTime: Date.now(),
225
+ attributes: {
226
+ 'node.name': nodeName,
227
+ 'node.type': nodeType,
228
+ ...attributes,
229
+ },
230
+ events: [],
231
+ links: [],
232
+ status: 'unset',
233
+ };
234
+ this.currentTraceContext = {
235
+ traceId,
236
+ spanId,
237
+ traceFlags: 1,
238
+ };
239
+ this.spanStack.push(span);
240
+ return this.createSpanScope(span);
241
+ }
242
+ /**
243
+ * Start a tool execution span
244
+ */
245
+ startToolSpan(toolName, attributes) {
246
+ const parentSpan = this.spanStack[this.spanStack.length - 1];
247
+ const traceId = parentSpan?.traceId ?? generateTraceId();
248
+ const spanId = generateSpanId();
249
+ const span = {
250
+ traceId,
251
+ spanId,
252
+ parentSpanId: parentSpan?.spanId,
253
+ name: `tool:${toolName}`,
254
+ kind: 'client',
255
+ startTime: Date.now(),
256
+ attributes: {
257
+ 'tool.name': toolName,
258
+ ...attributes,
259
+ },
260
+ events: [],
261
+ links: [],
262
+ status: 'unset',
263
+ };
264
+ this.spanStack.push(span);
265
+ return this.createSpanScope(span);
266
+ }
267
+ /**
268
+ * Start a custom span
269
+ */
270
+ startSpan(name, kind = 'internal', attributes) {
271
+ const parentSpan = this.spanStack[this.spanStack.length - 1];
272
+ const traceId = parentSpan?.traceId ?? generateTraceId();
273
+ const spanId = generateSpanId();
274
+ const span = {
275
+ traceId,
276
+ spanId,
277
+ parentSpanId: parentSpan?.spanId,
278
+ name,
279
+ kind,
280
+ startTime: Date.now(),
281
+ attributes: { ...attributes },
282
+ events: [],
283
+ links: [],
284
+ status: 'unset',
285
+ };
286
+ this.spanStack.push(span);
287
+ return this.createSpanScope(span);
288
+ }
289
+ /**
290
+ * Create a span scope with lifecycle methods
291
+ */
292
+ createSpanScope(span) {
293
+ return {
294
+ span,
295
+ end: (status = 'ok', message) => {
296
+ span.endTime = Date.now();
297
+ span.status = status;
298
+ if (message) {
299
+ span.statusMessage = message;
300
+ }
301
+ const idx = this.spanStack.indexOf(span);
302
+ if (idx !== -1) {
303
+ this.spanStack.splice(idx, 1);
304
+ }
305
+ const parentSpan = this.spanStack[this.spanStack.length - 1];
306
+ if (parentSpan) {
307
+ this.currentTraceContext = {
308
+ traceId: parentSpan.traceId,
309
+ spanId: parentSpan.spanId,
310
+ traceFlags: 1,
311
+ };
312
+ }
313
+ this.completedSpans.push(span);
314
+ },
315
+ addEvent: (name, attributes) => {
316
+ span.events.push({
317
+ name,
318
+ timestamp: Date.now(),
319
+ attributes,
320
+ });
321
+ },
322
+ setAttribute: (key, value) => {
323
+ span.attributes[key] = value;
324
+ },
325
+ setAttributes: (attributes) => {
326
+ Object.assign(span.attributes, attributes);
327
+ },
328
+ recordException: (error) => {
329
+ span.events.push({
330
+ name: 'exception',
331
+ timestamp: Date.now(),
332
+ attributes: {
333
+ 'exception.type': error.name,
334
+ 'exception.message': error.message,
335
+ 'exception.stacktrace': error.stack,
336
+ },
337
+ });
338
+ span.status = 'error';
339
+ span.statusMessage = error.message;
340
+ },
341
+ };
342
+ }
343
+ /**
344
+ * Add a link between spans
345
+ */
346
+ addLink(span, link) {
347
+ span.links.push(link);
348
+ }
349
+ /**
350
+ * Get current active span
351
+ */
352
+ getCurrentSpan() {
353
+ return this.spanStack[this.spanStack.length - 1];
354
+ }
355
+ /**
356
+ * Flush completed spans to exporter
357
+ */
358
+ async flush() {
359
+ if (!this.isSampled() || this.completedSpans.length === 0) {
360
+ return;
361
+ }
362
+ const spansToExport = [...this.completedSpans];
363
+ this.completedSpans = [];
364
+ await this.exporter.export(spansToExport);
365
+ }
366
+ /**
367
+ * Shutdown tracer and flush remaining spans
368
+ */
369
+ async shutdown() {
370
+ await this.flush();
371
+ await this.exporter.shutdown();
372
+ }
373
+ /**
374
+ * Run a function with automatic span creation
375
+ */
376
+ async trace(name, fn, options) {
377
+ const scope = this.startSpan(name, options?.kind, options?.attributes);
378
+ try {
379
+ const result = await fn(scope);
380
+ scope.end('ok');
381
+ return result;
382
+ }
383
+ catch (error) {
384
+ scope.recordException(error);
385
+ scope.end('error', error.message);
386
+ throw error;
387
+ }
388
+ }
389
+ }
390
+ /**
391
+ * Create a tracer instance
392
+ */
393
+ export function createTracer(config) {
394
+ return new WorkflowTracer(config);
395
+ }
396
+ /**
397
+ * Global tracer instance for convenience
398
+ */
399
+ let globalTracer = null;
400
+ export function getGlobalTracer() {
401
+ if (!globalTracer) {
402
+ globalTracer = new WorkflowTracer({ enabled: false });
403
+ }
404
+ return globalTracer;
405
+ }
406
+ export function setGlobalTracer(tracer) {
407
+ globalTracer = tracer;
408
+ }
409
+ //# sourceMappingURL=tracer.js.map