Python SDK for AI agent monitoring, LLM cost tracking, benchmarking, and more. Integrates with most LLMs and agent frameworks including CrewAI, Agno, OpenAI Agents SDK, Langchain, Autogen, AG2, and CamelAI
Python agentagentopsagents-sdkaianthropicautogencost-estimationcrewaievalsevaluation-metricsgroqlangchainllmmistralollamaopenaiopenai-agents
add back lib (#1222)
Alex Reibmandf8d101f67ed
diff --git a/.gitignore b/.gitignoreindex 6cff8d65..0b631f2d 100644--- a/.gitignore+++ b/.gitignore@@ -15,6 +15,7 @@ downloads/eggs/.eggs/lib/+!app/dashboard/lib/lib64/parts/sdist/diff --git a/app/dashboard/lib/api-client.ts b/app/dashboard/lib/api-client.tsnew file mode 100644index 00000000..0b992281--- /dev/null+++ b/app/dashboard/lib/api-client.ts@@ -0,0 +1,180 @@+import * as Sentry from '@sentry/nextjs';++const API_URL = process.env.NEXT_PUBLIC_API_URL;++export class ApiError extends Error {+ status: number;+ responseBody: any;+ endpoint: string;++ constructor(message: string, status: number, responseBody?: any, endpoint?: string) {+ super(message);+ this.name = 'ApiError';+ this.status = status;+ this.responseBody = responseBody;+ this.endpoint = endpoint || 'unknown';+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, ApiError);+ }+ }+}++/**+ * Creates a user-friendly error message based on the error type and status+ */+function getUserFriendlyErrorMessage(error: any, endpoint: string): string {+ if (error instanceof ApiError) {+ switch (error.status) {+ case 401:+ return 'Your session has expired. Please sign in again.';+ case 403:+ return "You don't have permission to access this resource.";+ case 404:+ return 'The requested resource was not found.';+ case 429:+ return 'Too many requests. Please wait a moment and try again.';+ case 500:+ return 'A server error occurred. Our team has been notified.';+ case 502:+ case 503:+ case 504:+ return 'The service is temporarily unavailable. Please try again in a few moments.';+ default:+ return 'An unexpected error occurred. Please try again.';+ }+ }++ // Network or other errors+ if (error.message?.includes('fetch')) {+ return 'Unable to connect to the server. Please check your internet connection and try again.';+ }++ return 'An unexpected error occurred. Please try again.';+}++/**+ * Reports error to Sentry with additional context+ */+function reportErrorToSentry(error: any, endpoint: string, context: Record<string, any> = {}) {+ Sentry.withScope((scope: any) => {+ scope.setTag('error_source', 'api_client');+ scope.setTag('endpoint', endpoint);+ scope.setContext('api_request', {+ endpoint,+ url: `${API_URL}${endpoint}`,+ ...context,+ });++ if (error instanceof ApiError) {+ scope.setTag('api_status', error.status);+ scope.setLevel('error');+ scope.setContext('response_body', error.responseBody);+ } else {+ scope.setTag('error_type', 'network_error');+ scope.setLevel('error');+ }++ Sentry.captureException(error);+ });+}++/**+ * Performs an authenticated fetch request to the backend API using a session cookie.+ * Handles retrieving the session_id cookie and adding the Authorization header.+ *+ * @param endpoint - The API endpoint path (e.g., '/opsboard/projects').+ * @param options - Optional fetch options (method, body, etc.). Defaults to GET.+ * @returns The JSON response data.+ * @throws {ApiError} If the API returns an error status or fetch fails.+ * @throws {Error} If session_id cookie is not found or API URL is missing.+ */+export async function fetchAuthenticatedApi<T = any>(+ endpoint: string,+ options: RequestInit = {},+): Promise<T> {+ if (!API_URL) {+ throw new Error('NEXT_PUBLIC_API_URL environment variable is not set.');+ }++ const headers = new Headers(options.headers || {});+ if (!headers.has('Content-Type') && options.body) {+ headers.set('Content-Type', 'application/json');+ }++ const fetchOptions: RequestInit = {+ ...options,+ headers,+ credentials: 'include',+ };++ const targetUrl = `${API_URL}${endpoint}`;++ try {+ const response = await fetch(targetUrl, fetchOptions);+ if (!response.ok) {+ let errorBody;+ try {+ errorBody = await response.json();+ } catch (e) {+ try {+ errorBody = await response.text();+ } catch (readErr) {+ errorBody = 'Failed to read error response body';+ }+ }+ console.error(`[API Client] API Error ${response.status} for ${endpoint}:`, errorBody);+ throw new ApiError(+ `API request failed with status ${response.status}`,+ response.status,+ errorBody,+ endpoint,+ );+ }++ if (response.status === 204) {+ return undefined as T;+ }++ const data: T = await response.json();+ return data;+ } catch (error) {+ if (error instanceof ApiError) {+ // Report API errors to Sentry with context+ reportErrorToSentry(error, endpoint, {+ status: error.status,+ responseBody: error.responseBody,+ });++ // Check for 401 Unauthorized specifically+ if (error.status === 401) {+ // Ensure this runs only on the client side+ if (typeof window !== 'undefined') {+ console.warn('[API Client] Received 401 Unauthorized for ${endpoint}.');+ // Prevent infinite loops if signin page itself triggers a 401 somehow+ if (window.location.pathname !== '/signin') {+ window.location.href = '/signin';+ }+ // Throw a specific error to signal the call failed due to auth and redirection occurred.+ throw new Error('Unauthorized. Redirecting to signin.');+ } else {+ // If not client-side (SSR/build), just re-throw the original error.+ // The caller might handle server-side redirection if needed.+ throw error;+ }+ }+ // Re-throw other ApiErrors with user-friendly message+ const userMessage = getUserFriendlyErrorMessage(error, endpoint);+ throw new Error(userMessage);+ } else {+ // Report network/unexpected errors to Sentry+ reportErrorToSentry(error, endpoint, {+ error_type: 'network_or_unexpected',+ original_message: (error as Error).message,+ });++ console.error(`[API Client] Network or unexpected error for ${endpoint}:`, error);+ const userMessage = getUserFriendlyErrorMessage(error, endpoint);+ throw new Error(userMessage);+ }+ }+}diff --git a/app/dashboard/lib/api/orgs.ts b/app/dashboard/lib/api/orgs.tsnew file mode 100644index 00000000..eb7ecddd--- /dev/null+++ b/app/dashboard/lib/api/orgs.ts@@ -0,0 +1,396 @@+import { IOrg } from '@/types/IOrg';+import { fetchAuthenticatedApi, ApiError } from '@/lib/api-client';++/**+ * Fetches the list of organizations for the authenticated user.+ * Uses JWT authentication via fetchAuthenticatedApi.+ */+export const fetchOrgsAPI = async (): Promise<IOrg[]> => {+ try {+ const orgs = await fetchAuthenticatedApi<IOrg[]>('/opsboard/orgs');+ return orgs ?? [];+ } catch (error) {+ console.error('Error fetching organizations:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to fetch organizations: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};++export interface IOrgInviteResponse {+ inviter_id: string;+ invitee_email: string;+ org_id: string;+ role: string;+ org_name: string;+ created_at?: string;+}++export interface IOrgInviteWithEmails {+ invitee_email: string;+ inviter_email: string;+ role: string;+ org_id: string;+ org_name: string;+ created_at?: string;+ user_exists?: boolean;+}++export interface IUserOrg {+ user_id: string;+ org_id: string;+ role: string;+ user_email: string;+ is_paid: boolean;+}++export interface IOrgDetailResponse extends IOrg {+ users: IUserOrg[];+}++export const fetchOrgDetailAPI = async (orgId: string): Promise<IOrgDetailResponse | null> => {+ if (!orgId) {+ console.error('[fetchOrgDetailAPI] Org ID is required.');+ return null;+ }+ const endpoint = `/opsboard/orgs/${orgId}`;+ try {+ const orgDetail = await fetchAuthenticatedApi<IOrgDetailResponse>(endpoint, {+ method: 'GET',+ headers: { Accept: 'application/json' },+ });+ return orgDetail || null;+ } catch (error) {+ console.error(`[fetchOrgDetailAPI] Error fetching details for org ${orgId}:`, error);+ if (+ error instanceof ApiError &&+ (error.status === 401 || error.status === 403 || error.status === 404)+ ) {+ return null;+ }+ throw error;+ }+};++export const fetchOrgInvitesAPI = async (): Promise<IOrgInviteResponse[] | null> => {+ const endpoint = '/opsboard/orgs/invites';+ try {+ const invites = await fetchAuthenticatedApi<IOrgInviteResponse[]>(endpoint, {+ method: 'GET',+ headers: { Accept: 'application/json' },+ });+ return invites || [];+ } catch (error) {+ console.error('[fetchOrgInvitesAPI] Error fetching invites:', error);+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {+ return null;+ }+ throw error;+ }+};++export const fetchMyPendingInvitesAPI = fetchOrgInvitesAPI;++export interface CreateOrgPayload {+ name: string;+}++export const createOrgAPI = async (payload: CreateOrgPayload): Promise<IOrg | null> => {+ const endpoint = '/opsboard/orgs/create';+ try {+ const createdOrg = await fetchAuthenticatedApi<IOrg>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(payload),+ });+ return createdOrg || null;+ } catch (error) {+ console.error('[createOrgAPI] Error creating org:', error);+ throw error;+ }+};++export const acceptOrgInviteAPI = async (+ orgId: string,+): Promise<{ success: boolean; message?: string } | null> => {+ const endpoint = `/opsboard/orgs/${orgId}/accept`;+ try {+ const response = await fetchAuthenticatedApi<{ success: boolean; message?: string }>(endpoint, {+ method: 'POST',+ headers: {+ Accept: 'application/json',+ },+ });+ return response || { success: false, message: 'No response from API' };+ } catch (error) {+ console.error(`[acceptOrgInviteAPI] Error accepting invite for org ${orgId}:`, error);+ if (error instanceof ApiError) {+ if (error.status === 401) {+ return {+ success: false,+ message: 'Authentication required. Your session may still be initializing.',+ };+ } else if (error.status === 404) {+ return {+ success: false,+ message: 'Invitation not found. It may have been revoked or already accepted.',+ };+ } else if (error.status === 400) {+ return {+ success: false,+ message: error.responseBody?.detail || 'Invalid invitation request.',+ };+ }+ return { success: false, message: error.message || `API Error ${error.status}` };+ }+ throw error;+ }+};++export interface UpdateOrgPayload {+ name: string;+}++export const updateOrgAPI = async (+ orgId: string,+ payload: UpdateOrgPayload,+): Promise<IOrg | null> => {+ if (!orgId) {+ console.error('[updateOrgAPI] Org ID is required.');+ return null;+ }+ const endpoint = `/opsboard/orgs/${orgId}/update`;+ try {+ const updatedOrg = await fetchAuthenticatedApi<IOrg>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(payload),+ });+ return updatedOrg || null;+ } catch (error) {+ console.error(`[updateOrgAPI] Error updating org ${orgId}:`, error);+ throw error;+ }+};++export interface InviteOrgMemberPayload {+ email: string;+ role: string;+}++export const inviteOrgMemberAPI = async (+ orgId: string,+ payload: InviteOrgMemberPayload,+): Promise<{ success: boolean; message?: string } | null> => {+ if (!orgId) {+ console.error('[inviteOrgMemberAPI] Org ID is required.');+ return { success: false, message: 'Org ID is required' };+ }+ const endpoint = `/opsboard/orgs/${orgId}/invite`;+ try {+ const normalizedPayload = {+ ...payload,+ email: payload.email.toLowerCase(),+ };+ const response = await fetchAuthenticatedApi<{ success: boolean; message?: string }>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(normalizedPayload),+ });+ return response || { success: false, message: 'No response from API' };+ } catch (error) {+ console.error(`[inviteOrgMemberAPI] Error inviting user to org ${orgId}:`, error);+ if (error instanceof ApiError) {+ return {+ success: false,+ message: error.responseBody?.detail || error.message || `API Error ${error.status}`,+ };+ }+ throw error;+ }+};++export interface RemoveOrgMemberPayload {+ user_id: string;+}++export const removeOrgMemberAPI = async (+ orgId: string,+ payload: RemoveOrgMemberPayload,+): Promise<{ success: boolean; message?: string } | null> => {+ if (!orgId) {+ console.error('[removeOrgMemberAPI] Org ID is required.');+ return { success: false, message: 'Org ID is required' };+ }+ const endpoint = `/opsboard/orgs/${orgId}/members/remove`;+ try {+ const response = await fetchAuthenticatedApi<{ success: boolean; message?: string }>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(payload),+ });+ return response || { success: false, message: 'No response from API' };+ } catch (error) {+ console.error(`[removeOrgMemberAPI] Error removing user from org ${orgId}:`, error);+ if (error instanceof ApiError) {+ return {+ success: false,+ message: error.responseBody?.detail || error.message || `API Error ${error.status}`,+ };+ }+ throw error;+ }+};++export interface UpdateOrgMemberRolePayload {+ user_id: string;+ role: string;+}++export const updateOrgMemberRoleAPI = async (+ orgId: string,+ payload: UpdateOrgMemberRolePayload,+): Promise<{ success: boolean; message?: string } | null> => {+ if (!orgId) {+ console.error('[updateOrgMemberRoleAPI] Org ID is required.');+ return { success: false, message: 'Org ID is required' };+ }+ const endpoint = `/opsboard/orgs/${orgId}/members/update`;+ try {+ const response = await fetchAuthenticatedApi<{ success: boolean; message?: string }>(endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify(payload),+ });+ return response || { success: false, message: 'No response from API' };+ } catch (error) {+ console.error(`[updateOrgMemberRoleAPI] Error updating role in org ${orgId}:`, error);+ if (error instanceof ApiError) {+ return {+ success: false,+ message: error.responseBody?.detail || error.message || `API Error ${error.status}`,+ };+ }+ throw error;+ }+};++// --- Add Delete Org API Function ---+export async function deleteOrgAPI(orgId: string): Promise<{ success: boolean; message?: string }> {+ // Assuming fetchAuthenticatedApi handles response parsing and error throwing+ return fetchAuthenticatedApi<{ success: boolean; message?: string }>(`/opsboard/orgs/${orgId}`, {+ method: 'DELETE',+ });+}+// --- End Delete Org API Function ---++export const fetchOrgInvitesForOrgAPI = async (orgId: string): Promise<IOrgInviteWithEmails[]> => {+ if (!orgId) {+ console.error('[fetchOrgInvitesForOrgAPI] Org ID is required.');+ return [];+ }+ const endpoint = `/opsboard/orgs/${orgId}/invites`;+ try {+ const invites = await fetchAuthenticatedApi<IOrgInviteWithEmails[]>(endpoint, {+ method: 'GET',+ headers: { Accept: 'application/json' },+ });+ return invites || [];+ } catch (error) {+ console.error(`[fetchOrgInvitesForOrgAPI] Error fetching invites for org ${orgId}:`, error);+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {+ return [];+ }+ throw error;+ }+};++/**+ * Fetches pending invitations sent BY an organization (for admins to manage).+ * This is an alias for fetchOrgInvitesForOrgAPI with a clearer name.+ */+export const fetchOrgSentInvitesAPI = fetchOrgInvitesForOrgAPI;++export const revokeOrgInviteAPI = async (+ orgId: string,+ email: string,+): Promise<{ success: boolean; message?: string }> => {+ if (!orgId || !email) {+ console.error('[revokeOrgInviteAPI] Org ID and email are required.');+ return { success: false, message: 'Org ID and email are required' };+ }+ const normalizedEmail = email.toLowerCase();+ const endpoint = `/opsboard/orgs/${orgId}/invites/${encodeURIComponent(normalizedEmail)}`;+ try {+ const response = await fetchAuthenticatedApi<{ success: boolean; message?: string }>(endpoint, {+ method: 'DELETE',+ headers: { Accept: 'application/json' },+ });+ return response || { success: false, message: 'No response from API' };+ } catch (error) {+ console.error(+ `[revokeOrgInviteAPI] Error revoking invite for ${email} in org ${orgId}:`,+ error,+ );+ if (error instanceof ApiError) {+ return {+ success: false,+ message: error.responseBody?.detail || error.message || `API Error ${error.status}`,+ };+ }+ throw error;+ }+};++export interface PreviewMemberAddCostResponse {+ immediate_charge: number;+ next_period_charge: number;+ billing_interval: string;+ period_end?: string;+ currency: string;+}++export const previewMemberAddCostAPI = async (+ orgId: string,+): Promise<PreviewMemberAddCostResponse | null> => {+ if (!orgId) {+ console.error('[previewMemberAddCostAPI] Org ID is required.');+ return null;+ }+ const endpoint = `/opsboard/orgs/${orgId}/preview-member-cost`;+ try {+ const response = await fetchAuthenticatedApi<PreviewMemberAddCostResponse>(endpoint, {+ method: 'GET',+ headers: { Accept: 'application/json' },+ });+ return response || null;+ } catch (error) {+ console.error(+ `[previewMemberAddCostAPI] Error fetching preview member add cost for org ${orgId}:`,+ error,+ );+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {+ return null;+ }+ throw error;+ }+};diff --git a/app/dashboard/lib/api/projects.ts b/app/dashboard/lib/api/projects.tsnew file mode 100644index 00000000..a1ccb3b4--- /dev/null+++ b/app/dashboard/lib/api/projects.ts@@ -0,0 +1,173 @@+import { IProject, IHostingProject } from '@/types/IProject';+import { fetchAuthenticatedApi, ApiError } from '@/lib/api-client';++/**+ * Fetches the list of projects for the authenticated user.+ * Uses JWT authentication via fetchAuthenticatedApi.+ */+export const fetchProjects = async (): Promise<IProject[]> => {+ try {+ const projects = await fetchAuthenticatedApi<IProject[]>('/opsboard/projects');+ return projects ?? [];+ } catch (error) {+ console.error('Error fetching projects:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to fetch projects: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};++export interface CreateProjectPayload {+ org_id: string;+ name: string;+}+export const createProjectAPI = async (payload: CreateProjectPayload): Promise<IProject> => {+ try {+ const createdProject = await fetchAuthenticatedApi<IProject>('/opsboard/projects', {+ method: 'POST',+ body: JSON.stringify(payload),+ });+ if (!createdProject) {+ throw new Error('API did not return created project data.');+ }+ return createdProject;+ } catch (error) {+ console.error('Error creating project:', error);+ if (error instanceof ApiError) {+ throw new Error(+ 'Failed to create project. Please try again or contact support if the issue persists.',+ );+ } else {+ throw error;+ }+ }+};++export interface DeleteProjectPayload {+ projectId: string;+}+export const deleteProjectAPI = async (+ payload: DeleteProjectPayload,+): Promise<{ success: boolean; message?: string }> => {+ try {+ // Use fetchAuthenticatedApi. Assuming 200/204 on success based on schema StatusResponse+ // The schema shows POST, adhering to that.+ const response = await fetchAuthenticatedApi<{ message?: string }>(+ `/opsboard/projects/${payload.projectId}/delete`,+ { method: 'POST' },+ );+ return { success: true, message: response?.message || 'Project deleted successfully' };+ } catch (error) {+ console.error('Error deleting project:', error);+ if (error instanceof ApiError) {+ return {+ success: false,+ message: `Failed to delete project: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ };+ } else {+ return { success: false, message: (error as Error).message };+ }+ }+};++export interface RenameProjectPayload {+ projectId: string;+ newName: string;+}+export const renameProjectAPI = async (payload: RenameProjectPayload): Promise<IProject> => {+ try {+ const updatedProject = await fetchAuthenticatedApi<IProject>(+ `/opsboard/projects/${payload.projectId}/update`,+ {+ method: 'POST',+ body: JSON.stringify({ name: payload.newName }),+ },+ );+ if (!updatedProject) {+ throw new Error('API did not return updated project data.');+ }+ return updatedProject;+ } catch (error) {+ console.error('Error renaming project:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to rename project: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};++export interface RotateApiKeyPayload {+ projectId: string;+}+// Response should be the updated Project object according to schema+export const rotateApiKeyAPI = async (payload: RotateApiKeyPayload): Promise<IProject> => {+ try {+ const updatedProject = await fetchAuthenticatedApi<IProject>(+ `/opsboard/projects/${payload.projectId}/regenerate-key`,+ { method: 'POST' },+ );+ if (!updatedProject) {+ throw new Error('API did not return project data after key rotation.');+ }+ return updatedProject;+ } catch (error) {+ console.error('Error rotating API key:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to rotate API key: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};++export const fetchDeployments = async (): Promise<IHostingProject[]> => {+ try {+ const deployments = await fetchAuthenticatedApi<IHostingProject[]>('/deploy/deployments');+ return deployments ?? [];+ } catch (error) {+ console.error('Error fetching deployments:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to fetch deployments: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};++export interface DeploymentJob {+ id: string;+ queued_at: string;+ status: string;+ message: string;+}++export interface DeploymentHistoryResponse {+ jobs: DeploymentJob[];+}++export const fetchDeploymentHistory = async (projectId: string): Promise<DeploymentHistoryResponse> => {+ try {+ const history = await fetchAuthenticatedApi<DeploymentHistoryResponse>(`/deploy/deployments/${projectId}/history`);+ return history ?? { jobs: [] };+ } catch (error) {+ console.error('Error fetching deployment history:', error);+ if (error instanceof ApiError) {+ throw new Error(+ `Failed to fetch deployment history: ${error.status} - ${JSON.stringify(error.responseBody)}`,+ );+ } else {+ throw error;+ }+ }+};diff --git a/app/dashboard/lib/api/user.ts b/app/dashboard/lib/api/user.tsnew file mode 100644index 00000000..6b689b79--- /dev/null+++ b/app/dashboard/lib/api/user.ts@@ -0,0 +1,26 @@+import { IUser } from '@/types/IUser';+import { fetchAuthenticatedApi, ApiError } from '../api-client'; // Import the new client++/**+ * Fetches the data for the currently authenticated user using the backend API.+ */+export const fetchUserAPI = async (): Promise<IUser | null> => {+ const endpoint = '/opsboard/users/me'; // Correct backend endpoint++ try {+ const user = await fetchAuthenticatedApi<IUser>(endpoint, {+ method: 'GET',+ headers: {+ Accept: 'application/json',+ },+ });++ return user || null;+ } catch (error) {+ console.error('[fetchUserAPI] Error fetching user:', error);+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {+ return null;+ }+ throw error;+ }+};diff --git a/app/dashboard/lib/billing-utils.ts b/app/dashboard/lib/billing-utils.tsnew file mode 100644index 00000000..2433a307--- /dev/null+++ b/app/dashboard/lib/billing-utils.ts@@ -0,0 +1,67 @@+interface StripePricing {+ seat?: { amount: number; interval: string };+ tokens?: { amount: number };+ spans?: { amount: number };+}++/**+ * Calculate token cost using standardized billing rates+ * @param tokenCount - Number of tokens+ * @param allPricing - Stripe pricing data+ * @returns Cost in dollars+ */+export function calculateTokenCost(tokenCount: number, allPricing?: StripePricing): number {+ if (!tokenCount || tokenCount <= 0) return 0;++ // Price per 1M tokens in dollars+ const tokenPricePerMillion = ((allPricing?.tokens?.amount || 0.02) * 1000) / 100;++ return (tokenCount / 1_000_000) * tokenPricePerMillion;+}++/**+ * Calculate span cost using standardized billing rates+ * @param spanCount - Number of spans+ * @param allPricing - Stripe pricing data+ * @returns Cost in dollars+ */+export function calculateSpanCost(spanCount: number, allPricing?: StripePricing): number {+ if (!spanCount || spanCount <= 0) return 0;++ // Price per 1K spans in dollars+ const spanPricePerThousand = (allPricing?.spans?.amount || 0.01) / 100;++ return (spanCount / 1_000) * spanPricePerThousand;+}++/**+ * Calculate total usage cost (tokens + spans)+ * @param tokenCount - Number of tokens+ * @param spanCount - Number of spans+ * @param allPricing - Stripe pricing data+ * @returns Total cost in dollars+ */+export function calculateUsageCost(+ tokenCount: number,+ spanCount: number,+ allPricing?: StripePricing,+): number {+ return calculateTokenCost(tokenCount, allPricing) + calculateSpanCost(spanCount, allPricing);+}++/**+ * Get pricing rates for display+ * @param allPricing - Stripe pricing data+ * @returns Pricing rates in dollars+ */+export function getPricingRates(allPricing?: StripePricing) {+ const tokenPricePerMillion = ((allPricing?.tokens?.amount || 0.02) * 1000) / 100;+ const spanPricePerThousand = (allPricing?.spans?.amount || 0.01) / 100;++ return {+ tokenPricePerMillion,+ spanPricePerThousand,+ seatPrice: (allPricing?.seat?.amount || 4000) / 100,+ seatInterval: allPricing?.seat?.interval || 'month',+ };+}diff --git a/app/dashboard/lib/idb.ts b/app/dashboard/lib/idb.tsnew file mode 100644index 00000000..5fd90f42--- /dev/null+++ b/app/dashboard/lib/idb.ts@@ -0,0 +1,107 @@+'use client';++import { openDB, DBSchema, IDBPDatabase, deleteDB } from 'idb';+import { ISessionAndStats } from './interfaces';+import { addBreadcrumb, captureException } from '@sentry/nextjs';++interface DB extends DBSchema {+ sessions: {+ key: string;+ value: ISessionAndStats;+ indexes: { init_timestamp: string };+ };+}++async function getDB(): Promise<IDBPDatabase<DB>> {+ return openDB<DB>('AgentOpsCache', 1, {+ upgrade(db) {+ if (!db.objectStoreNames.contains('sessions')) {+ const store = db.createObjectStore('sessions', { keyPath: 'id' });+ store.createIndex('init_timestamp', 'init_timestamp');+ }+ },+ });+}++export async function setIdbSessions(sessions: ISessionAndStats[]): Promise<void> {+ try {+ const db = await getDB();+ const tx = db.transaction('sessions', 'readwrite');+ const store = tx.objectStore('sessions');++ for (const session of sessions) {+ store.put(session);+ }++ return tx.done;+ } catch (e) {+ console.error(e);+ addBreadcrumb({+ category: 'Sessions',+ data: { sessions: sessions },+ });+ captureException(e);+ }+}++export async function getIdbSessions(): Promise<ISessionAndStats[]>;+export async function getIdbSessions(id: string): Promise<ISessionAndStats | undefined>;+export async function getIdbSessions(id?: string) {+ const db = await getDB();+ if (id) {+ return db.get('sessions', id);+ }+ const sessions = db.transaction('sessions').store.index('init_timestamp');+ return (await sessions.getAll()).reverse();+}++export async function clearIdbSessions(): Promise<void> {+ const db = await getDB();+ const tx = db.transaction('sessions', 'readwrite');+ const store = tx.objectStore('sessions');+ store.clear();++ return tx.done;+}++export async function deleteIdbSessions(ids: string[]): Promise<void> {+ const db = await getDB();+ const tx = db.transaction('sessions', 'readwrite');+ const store = tx.objectStore('sessions');++ for (const id of ids) {+ store.delete(id);+ }++ return tx.done;+}++export async function deleteCache() {+ await deleteDB('AgentOpsCache');+}++export function setOnboardingSkipped(isSkipped: boolean): void {+ if (typeof window !== 'undefined') {+ localStorage.setItem('onboardingSkipped', isSkipped.toString());+ }+}++export function getOnboardingSkipped(): boolean | undefined {+ if (typeof window !== 'undefined') {+ const onboardingSkipped = JSON.parse(localStorage.getItem('onboardingSkipped') ?? 'null');+ return JSON.parse(onboardingSkipped) ?? undefined;+ }+ return undefined;+}++export function setTutorialSkipped(isSkippedTutorial: boolean): void {+ if (typeof window !== 'undefined') {+ localStorage.setItem('tutorialSkipped', isSkippedTutorial.toString());+ }+}+export function getTutorialSkipped(): boolean {+ if (typeof window !== 'undefined') {+ return JSON.parse(localStorage.getItem('tutorialSkipped') || 'false');+ }+ return false;+}diff --git a/app/dashboard/lib/interfaces.ts b/app/dashboard/lib/interfaces.tsnew file mode 100644index 00000000..d4c2e3bf--- /dev/null+++ b/app/dashboard/lib/interfaces.ts@@ -0,0 +1,389 @@+import { Tables } from '@/lib/types_db';++export interface ISessionAndStats extends Omit<Tables<'sessions'>, 'host_env'> {+ host_env: HostEnv | null;+ stats: Tables<'stats'>;+}+export type HostEnv = {+ OS?: OS;+ RAM?: RAM;+ CPU?: CPU;+ SDK?: SDK;+ Disk?: Disk;+ 'Installed Packages'?: InstalledPackages;+ 'Virtual Environment'?: VirtualEnvironment;+ 'Project Working Directory'?: ProjectWorkingDirectory;+};++type OS = {+ OS: string;+ Hostname: string;+ 'OS Release': string;+ 'OS Version': string;+};++type RAM = {+ Used: string;+ Total: string;+ Available: string;+ Percentage: string;+};++type CPU = {+ 'CPU Usage': string;+ 'Total cores': number;+ 'Physical cores': number;+};++type SDK = {+ 'Python Version': string;+ 'System Packages': SystemPackages;+ 'AgentOps SDK Version': string;+};++export type SystemPackages = {+ [key: string]: string;+};++type Disk = {+ [key: string]: {+ Free: string;+ Used: string;+ Total: string;+ Mountpoint: string;+ Percentage: string;+ };+};++type InstalledPackages = {+ 'Installed Packages': {+ [key: string]: string;+ };+};++type VirtualEnvironment = {+ 'Virtual Environment': string;+};++type ProjectWorkingDirectory = {+ 'Project Working Directory': string;+};++/*+ * Prompt Messages and Completion Messages are validated against a json schema before+ * being stored in Supabase. While Supabase only knows that the fields are JSON, we+ * know their full shapes.+ */+export type llms = Omit<Tables<'llms'>, 'prompt' | 'completion'> & {+ prompt: prompt;+ completion: completion;+};++export type prompt = chatmlPrompt | promptCompletionString;+export type completion = {+ type: 'string' | 'chatml';+ string?: string;+ messages?: chatmlTextMessage;+};++export type chatmlPrompt = {+ type: 'chatml';+ messages: chatmlTextMessage[] | chatmlImageMessage[];+};++export type toolCall = {+ id: string;+ type: 'function';+ function: {+ name: string;+ arguments: string;+ };+};++export type functionCall = toolCall;++type chatmlTextMessage = {+ role: string;+ content: string;+ tool_calls?: {+ id: string;+ function: {+ name: string;+ arguments: string;+ };+ }[];+};++type chatmlImageMessage = {+ role: 'user' | 'assistant';+ content:+ | {+ type: 'text';+ text: string;+ }+ | {+ type: 'image_url';+ image_url: {+ url: string;+ };+ };+};++type promptCompletionString = {+ type: 'string';+ string: string;+};++export interface IExtendedSession {+ id: string;+ agents: Tables<'agents'>[] | null;+ threads: Tables<'threads'>[] | null;+ llms: llms[] | null;+ actions: Tables<'actions'>[] | null;+ tools: Tables<'tools'>[] | null;+ errors: Tables<'errors'>[] | null;+}++export interface ILlms extends llms {+ type: 'LLM Call';+}++export interface ITools extends Tables<'tools'> {+ type: 'Tool';+}++export interface IActions extends Tables<'actions'> {+ type: 'Action';+}++export interface IErrors extends Tables<'errors'> {+ type: 'Error';+}++export type IEvent = IActions | ILlms | ITools;++/**+ * Pagination parameters for API requests+ */+export interface PaginationParams {+ limit?: number;+ offset?: number;+}++/**+ * Session representation+ */+export interface Session {+ id: string;+ projectId: string;+ startTime: Date;+ endTime: Date | null;+ durationMs: number;+ endState: string;+ tags: string[];+ metadata: Record<string, any>;+}++/**+ * Trace based on OpenTelemetry span+ */+export interface Trace {+ traceId: string;+ spanId: string;+ parentSpanId: string | null;+ name: string;+ startTime: Date;+ endTime: Date;+ durationNs: number;+ statusCode: 'UNSET' | 'OK' | 'ERROR';+ statusMessage: string;+ attributes: Record<string, any>;+ resourceAttributes: Record<string, any>;+ events: TraceEvent[];+ projectId: string;+}++/**+ * Event within a trace+ */+export interface TraceEvent {+ name: string;+ timestamp: Date;+ attributes: Record<string, any>;+}++/**+ * Session log based on OpenTelemetry log record+ */+export interface SessionLog {+ timestamp: Date;+ traceId: string | null;+ spanId: string | null;+ severityText: string;+ severityNumber: number;+ body: string | Record<string, any>;+ attributes: Record<string, any>;+ resourceAttributes: Record<string, any>;+}++/**+ * Session metric based on OpenTelemetry metric+ */+export interface SessionMetric {+ timestamp: Date;+ name: string;+ description: string;+ unit: string;+ dataType: 'GAUGE' | 'SUM' | 'HISTOGRAM' | 'EXPONENTIAL_HISTOGRAM' | 'SUMMARY';+ value: number | Record<string, any>;+ attributes: Record<string, any>;+ resourceAttributes: Record<string, any>;+}++/**+ * Session statistics+ */+export interface SessionStats {+ sessionId: string;+ projectId: string;+ startTime: Date;+ endTime: Date | null;+ durationMs: number;+ endState: string;+ traceCount: number;+ logCount: number;+ metricCount: number;+ errorCount: number;+}++/**+ * OpenTelemetry severity numbers+ * Based on https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitynumber+ */+export enum SeverityNumber {+ UNSPECIFIED = 0,+ TRACE = 1,+ TRACE2 = 2,+ TRACE3 = 3,+ TRACE4 = 4,+ DEBUG = 5,+ DEBUG2 = 6,+ DEBUG3 = 7,+ DEBUG4 = 8,+ INFO = 9,+ INFO2 = 10,+ INFO3 = 11,+ INFO4 = 12,+ WARN = 13,+ WARN2 = 14,+ WARN3 = 15,+ WARN4 = 16,+ ERROR = 17,+ ERROR2 = 18,+ ERROR3 = 19,+ ERROR4 = 20,+ FATAL = 21,+ FATAL2 = 22,+ FATAL3 = 23,+ FATAL4 = 24,+}++/**+ * OpenTelemetry severity text values+ * Based on https://opentelemetry.io/docs/specs/otel/logs/data-model/#field-severitytext+ */+export enum SeverityText {+ TRACE = 'TRACE',+ DEBUG = 'DEBUG',+ INFO = 'INFO',+ WARN = 'WARN',+ ERROR = 'ERROR',+ FATAL = 'FATAL',+}++/**+ * OpenTelemetry span status codes+ * Based on https://opentelemetry.io/docs/specs/otel/trace/api/#set-status+ */+export enum SpanStatusCode {+ UNSET = 'UNSET',+ OK = 'OK',+ ERROR = 'ERROR',+}++/**+ * OpenTelemetry metric data types+ * Based on https://opentelemetry.io/docs/specs/otel/metrics/data-model/+ */+export enum MetricDataType {+ GAUGE = 'GAUGE',+ SUM = 'SUM',+ HISTOGRAM = 'HISTOGRAM',+ EXPONENTIAL_HISTOGRAM = 'EXPONENTIAL_HISTOGRAM',+ SUMMARY = 'SUMMARY',+}++export interface ProjectMetrics {+ project_id: string;+ trace_count: number;+ span_count: {+ total: number;+ success: number;+ fail: number;+ unknown: number;+ indeterminate: number;+ };+ token_metrics: {+ prompt_tokens: number;+ completion_tokens: number;+ total_tokens: {+ all: number;+ success: number;+ fail: number;+ };+ total_cost: number | string;+ average_cost_per_session: string;+ avg_tokens: {+ all: string;+ success: string;+ fail: string;+ };+ by_model?: Record<string, number>;+ by_system?: {+ llm: number;+ [key: string]: number;+ };+ };+ duration_metrics: {+ min_duration_ns: number;+ max_duration_ns: number;+ avg_duration_ns: number;+ total_duration_ns: number;+ };+ success_datetime?: string[];+ fail_datetime?: string[];+ indeterminate_datetime?: string[];+ spans_per_trace?: Record<string, number>[];+ failed_traces_dates?: Record<string, number>[];+ trace_cost_dates?: Record<string, number>[];+ trace_durations?: number[];+ freeplan_truncated?: boolean;+}++export interface TraceMetrics {+ trace_id: string;+ token_metrics: {+ prompt_tokens: number;+ completion_tokens: number;+ total_tokens: number;+ total_cost: number;+ by_model: Record<string, number>;+ by_system: {+ llm: number;+ [key: string]: number;+ };+ };+ start_time: string;+ end_time: string;+ total_duration_ns: number;+}diff --git a/app/dashboard/lib/modelUtils.tsx b/app/dashboard/lib/modelUtils.tsxnew file mode 100644index 00000000..d2942e3e--- /dev/null+++ b/app/dashboard/lib/modelUtils.tsx@@ -0,0 +1,108 @@+import AnthropicIcon from '@/components/icons/AnthropicIcon';+import AgentstackIcon from '@/components/icons/AgentstackIcon';+import ChatgptIcon from '@/components/icons/ChatgptIcon';+import CohereIcon from '@/components/icons/CohereIcon';+import CrewIcon from '@/components/icons/CrewIcon';+import GeminiIcon from '@/components/icons/GeminiIcon';+import GroqIcon from '@/components/icons/GroqIcon';+import LangchainIcon from '@/components/icons/LangchainIcon';+import LitellmIcon from '@/components/icons/LitellmIcon';+import LlamaIndexIcon from '@/components/icons/LlamaIndexIcon';+import MicrosoftIcon from '@/components/icons/MicrosoftIcon';+import MistralAiIcon from '@/components/icons/MistralAiIcon';+import MultionIcon from '@/components/icons/MultionIcon';+import OllamaIcon from '@/components/icons/OllamaIcon';+import DeepseekIcon from '@/components/icons/DeepseekIcon';+import QwenIcon from '@/components/icons/QwenIcon';+import AG2Icon from '@/components/icons/AG2Icon';+import XAIIcon from '@/components/icons/XAIIcon';+import Logo from '@/components/icons/Logo';+import PerplexityIcon from '@/components/icons/PerplexityIcon';+import AgnoIcon from '@/components/icons/AgnoIcon/AgnoIcon';+import XpanderIcon from '@/components/icons/XpanderIcon';+import IBMIcon from '@/components/icons/IBMIcon';+import Mem0Icon from '@/components/icons/Mem0Icon';++const iconMap = {+ agentstack: <AgentstackIcon />,+ crewai: <CrewIcon />,+ openai: <ChatgptIcon />,+ swarm: <ChatgptIcon />,+ gpt: <ChatgptIcon />,+ cohere: <CohereIcon />,+ langchain: <LangchainIcon />,+ ollama: <OllamaIcon />,+ deepseek: <DeepseekIcon />,+ qwen: <QwenIcon />,+ groq: <GroqIcon />,+ mistralai: <MistralAiIcon />,+ mixtral: <MistralAiIcon />,+ anthropic: <AnthropicIcon />,+ claude: <AnthropicIcon />,+ multion: <MultionIcon />,+ llama: <LlamaIndexIcon />,+ autogen: <MicrosoftIcon />,+ ag2: <AG2Icon />,+ litellm: <LitellmIcon />,+ gemini: <GeminiIcon />,+ xai: <XAIIcon />,+ perplexity: <PerplexityIcon />,+ agno: <AgnoIcon />,+ xpander: <XpanderIcon />,+ watson: <IBMIcon />,+ mem0: <Mem0Icon />,+};++export const getIconForModel = (model: string): React.ReactNode | null => {+ if (!model || typeof model !== 'string') {+ return <Logo />;+ }+ const lowerModel = model.toLowerCase();++ // Check for specific model name patterns+ if (lowerModel.includes('grok')) {+ return iconMap.xai || <XAIIcon />;+ }++ // Check for o1, o2, o3, etc. pattern (GPT models)+ if (/o[0-9]/.test(lowerModel)) {+ return iconMap.gpt || <ChatgptIcon />;+ }++ // Check for -ada pattern (GPT models)+ if (lowerModel.includes('-ada')) {+ return iconMap.gpt || <ChatgptIcon />;+ }++ // Check for gemma pattern (Gemini models)+ if (lowerModel.includes('gemma')) {+ return iconMap.gemini || <GeminiIcon />;+ }++ // Check for mixtral pattern (Mistral models)+ if (lowerModel.includes('mixtral') || lowerModel.includes('mistral')) {+ return iconMap.mistralai || <MistralAiIcon />;+ }++ if (lowerModel.includes('perplexity')) {+ return iconMap.perplexity || <PerplexityIcon />;+ }+ if (lowerModel.includes('sonar')) {+ return iconMap.perplexity || <PerplexityIcon />;+ }++ // Check for GCP/Vertex/ADK patterns (Gemini models)+ if (+ lowerModel.includes('gcp') ||+ lowerModel.includes('google') ||+ lowerModel.includes('gemini') ||+ lowerModel.includes('vertex') ||+ lowerModel.includes('adk')+ ) {+ return iconMap.gemini || <GeminiIcon />;+ }++ // String includes matching for other models+ const match = Object.keys(iconMap).find((key) => lowerModel.includes(key));+ return match ? iconMap[match as keyof typeof iconMap] : <Logo />;+};diff --git a/app/dashboard/lib/number_formatting_utils.ts b/app/dashboard/lib/number_formatting_utils.tsnew file mode 100644index 00000000..ff00759d--- /dev/null+++ b/app/dashboard/lib/number_formatting_utils.ts@@ -0,0 +1,251 @@+import { formatDuration, intervalToDuration } from 'date-fns';++// Standard abbreviation config+const ABBREVIATIONS = [+ { threshold: 1e12, suffix: 'T' },+ { threshold: 1e9, suffix: 'B' },+ { threshold: 1e6, suffix: 'M' },+ { threshold: 1e3, suffix: 'K' },+] as const;++/**+ * Core number formatter - handles all abbreviation logic+ */+function formatWithAbbreviation(+ value: number,+ options: {+ decimals?: number;+ threshold?: number;+ forceAbbreviation?: boolean;+ } = {},+): { display: string; full: string } {+ const { decimals = 2, threshold = 1e6, forceAbbreviation = false } = options;++ const full = new Intl.NumberFormat('en-US', {+ maximumFractionDigits: decimals,+ useGrouping: true,+ }).format(value);++ if (!forceAbbreviation && Math.abs(value) < threshold) {+ return { display: full, full };+ }++ const abbrev = ABBREVIATIONS.find((a) => Math.abs(value) >= a.threshold);+ if (!abbrev) return { display: full, full };++ const scaled = value / abbrev.threshold;+ const display = `${scaled.toFixed(scaled >= 100 ? 0 : 1)}${abbrev.suffix}`;++ return { display, full };+}++/**+ * Format number with grouping+ */+export function formatNumber(number: string | number | null | undefined, decimals = 0): string {+ if (number == null) return '';++ const num = typeof number === 'string' ? parseFloat(number) : number;+ if (isNaN(num)) return '';++ return new Intl.NumberFormat('en-US', {+ maximumFractionDigits: Math.min(Math.max(0, decimals), 20),+ minimumFractionDigits: decimals,+ useGrouping: true,+ }).format(num);+}++/**+ * Format price with currency+ */+export function formatPrice(+ price: number | string | null | undefined,+ options: { currency?: string; locale?: string; decimals?: number } = {},+): string {+ const { currency = 'USD', locale = 'en-US', decimals = 2 } = options;++ if (price == null) return '';++ const num = typeof price === 'string' ? parseFloat(price) : price;+ if (isNaN(num)) return '';++ // Currency-specific defaults+ const currencyDecimals = { JPY: 0, KRW: 0, VND: 0 }[currency] ?? decimals;+ const finalDecimals = decimals !== 2 ? decimals : currencyDecimals;++ if (num === 0) {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: 0,+ maximumFractionDigits: 0,+ }).format(0);+ }++ // Handle tiny amounts+ const threshold = 1 / Math.pow(10, finalDecimals);+ if (num > 0 && num < threshold) {+ return `< ${new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: finalDecimals,+ maximumFractionDigits: finalDecimals,+ }).format(threshold)}`;+ }++ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: Math.min(finalDecimals, 6),+ maximumFractionDigits: Math.min(finalDecimals, 6),+ }).format(num);+}++/**+ * Format large prices with abbreviations+ */+export function formatLargePrice(+ price: number | string | null | undefined,+ options: { currency?: string; locale?: string; decimals?: number } = {},+): string {+ const { currency = 'USD', locale = 'en-US', decimals = 2 } = options;++ if (price == null) return '';++ const num = typeof price === 'string' ? parseFloat(price) : price;+ if (isNaN(num)) return '';++ if (num === 0) {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: 0,+ maximumFractionDigits: 0,+ }).format(0);+ }++ // Use abbreviation for amounts >= 100K+ if (Math.abs(num) < 100000) {+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ }).format(num);+ }++ const { display } = formatWithAbbreviation(Math.abs(num), {+ threshold: 100000,+ forceAbbreviation: true,+ });+ const currencySymbol = new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: 0,+ maximumFractionDigits: 0,+ })+ .format(0)+ .replace(/[\d\s]/g, '');++ return `${num < 0 ? '-' : ''}${currencySymbol}${display}`;+}++/**+ * Format tokens with abbreviations+ */+export function formatTokens(tokens: number | string | null | undefined): {+ display: string;+ full: string;+} {+ if (tokens == null) return { display: '0', full: '0' };++ const num = typeof tokens === 'string' ? parseFloat(tokens) : tokens;+ if (isNaN(num)) return { display: '0', full: '0' };++ return formatWithAbbreviation(num, { decimals: 0, threshold: 1e6 });+}++/**+ * Format cost with proper decimal handling+ */+export function formatCost(cost: number | string | null | undefined): string {+ if (cost == null) return '$0.000000';++ const num = typeof cost === 'string' ? parseFloat(cost) : cost;+ if (isNaN(num)) return '$0.000000';++ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: 6,+ maximumFractionDigits: 6,+ }).format(num);+}++/**+ * Format metric with prefix/suffix+ */+export function formatMetric(+ value: number | string | null | undefined,+ options: { prefix?: string; suffix?: string; defaultValue?: string } = {},+): string {+ if (value == null) return options.defaultValue || 'N/A';++ const num = typeof value === 'string' ? parseFloat(value) : value;+ if (isNaN(num)) return options.defaultValue || 'N/A';++ const { prefix = '', suffix = '' } = options;+ if (num === 0) return `${prefix}0${suffix}`;++ const decimals = num > 0 && num < 0.01 ? 3 : 2;+ return `${prefix}${num.toFixed(decimals)}${suffix}`;+}++/**+ * Format percentage+ */+export function formatPercentage(+ value: number | string | null | undefined,+ options: { alreadyMultiplied?: boolean; defaultValue?: string } = {},+): string {+ if (value == null) return options.defaultValue || 'N/A';++ const num = typeof value === 'string' ? parseFloat(value) : value;+ if (isNaN(num)) return options.defaultValue || 'N/A';++ const percentage = options.alreadyMultiplied ? num : num * 100;+ return `${percentage.toFixed(2)}%`;+}++/**+ * Format milliseconds duration+ */+export function formatMilliseconds(startDate: string, endDate: string, mss: number): string {+ if (!mss || isNaN(mss)) return 'N/A';++ const ms = mss / 1000000; // nanoseconds to milliseconds++ if (ms < 1000) {+ return `${(ms / 1000).toFixed(2)}s`;+ }++ const duration = intervalToDuration({+ start: new Date(startDate),+ end: new Date(endDate),+ });++ return formatDuration(duration, {+ format: ['days', 'hours', 'minutes', 'seconds'],+ delimiter: ' ',+ zero: false,+ })+ .replace(/(\d+)\s+day(?:s)?/gi, '$1d')+ .replace(/(\d+)\s+hour(?:s)?/gi, '$1h')+ .replace(/(\d+)\s+minute(?:s)?/gi, '$1m')+ .replace(/(\d+)\s+second(?:s)?/gi, '$1s');+}++/**+ * Format time in seconds+ */+export const formatTimeInSeconds = (ms: number): string => `${(ms / 1000).toFixed(2)}s`;diff --git a/app/dashboard/lib/otel.ts b/app/dashboard/lib/otel.tsnew file mode 100644index 00000000..702e0232--- /dev/null+++ b/app/dashboard/lib/otel.ts@@ -0,0 +1,100 @@+import { useState, useEffect } from 'react';++type QueryType = 'traces' | 'logs' | 'metrics';++interface UseOtelDataProps {+ queryType: QueryType;+ params: any;+ enabled?: boolean;+}++export function useOtelData<T>({ queryType, params, enabled = true }: UseOtelDataProps) {+ const [data, setData] = useState<T | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ useEffect(() => {+ if (!enabled) return;++ const fetchData = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const response = await fetch('/api/clickhouse', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ queryType,+ params,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to fetch data');+ }++ const result = await response.json();+ setData(result.data);+ } catch (err) {+ setError(err instanceof Error ? err : new Error(String(err)));+ } finally {+ setIsLoading(false);+ }+ };++ fetchData();+ }, [queryType, JSON.stringify(params), enabled]);++ return { data, isLoading, error };+}++// Types for trace data+export interface Trace {+ trace_id: string;+ service_name: string;+ start_time: string;+ end_time: string;+ duration_ms: number;+ status_code: string;+ // Add other fields as needed+}++export interface Span {+ span_id: string;+ trace_id: string;+ parent_span_id: string | null;+ name: string;+ start_time: string;+ end_time: string;+ duration_ms: number;+ service_name: string;+ status_code: string;+ attributes: Record<string, any>;+ events: Array<{+ name: string;+ timestamp: string;+ attributes: Record<string, any>;+ }>;+ // Add other fields as needed+}++export interface TraceQueryParams {+ project_id?: string;+ start_time?: string;+ end_time?: string;+ service_name?: string;+ span_name?: string;+ status_code?: string;+ limit?: number;+ offset?: number;+ // Add other query parameters as needed+}++export interface TraceSearchParams extends TraceQueryParams {+ query?: string;+ // Add other search-specific parameters+}diff --git a/app/dashboard/lib/posthog.ts b/app/dashboard/lib/posthog.tsnew file mode 100644index 00000000..d9fbfd7d--- /dev/null+++ b/app/dashboard/lib/posthog.ts@@ -0,0 +1,10 @@+import { PostHog } from 'posthog-node';++export default function PostHogClient() {+ const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {+ host: process.env.NEXT_PUBLIC_POSTHOG_HOST,+ flushAt: 1,+ flushInterval: 0,+ });+ return posthogClient;+}diff --git a/app/dashboard/lib/signin.ts b/app/dashboard/lib/signin.tsnew file mode 100644index 00000000..26f7da56--- /dev/null+++ b/app/dashboard/lib/signin.ts@@ -0,0 +1,2 @@+const defaultMethods = 'email,magic,google,github';+export const signInMethods = (process.env.NEXT_PUBLIC_SIGNIN_METHODS || defaultMethods).split(',');diff --git a/app/dashboard/lib/types_db.ts b/app/dashboard/lib/types_db.tsnew file mode 100644index 00000000..e5c1c5ed--- /dev/null+++ b/app/dashboard/lib/types_db.ts@@ -0,0 +1,981 @@+export type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];++export type Database = {+ public: {+ Tables: {+ actions: {+ Row: {+ action_type: string | null;+ agent_id: string;+ end_timestamp: string;+ id: string;+ init_timestamp: string;+ logs: string | null;+ params: string | null;+ returns: string | null;+ screenshot: string | null;+ session_id: string;+ };+ Insert: {+ action_type?: string | null;+ agent_id: string;+ end_timestamp: string;+ id?: string;+ init_timestamp: string;+ logs?: string | null;+ params?: string | null;+ returns?: string | null;+ screenshot?: string | null;+ session_id: string;+ };+ Update: {+ action_type?: string | null;+ agent_id?: string;+ end_timestamp?: string;+ id?: string;+ init_timestamp?: string;+ logs?: string | null;+ params?: string | null;+ returns?: string | null;+ screenshot?: string | null;+ session_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'actions_agent_id_fkey';+ columns: ['agent_id'];+ isOneToOne: false;+ referencedRelation: 'agents';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'actions_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ agents: {+ Row: {+ id: string;+ logs: string | null;+ name: string | null;+ session_id: string;+ };+ Insert: {+ id: string;+ logs?: string | null;+ name?: string | null;+ session_id: string;+ };+ Update: {+ id?: string;+ logs?: string | null;+ name?: string | null;+ session_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'agents_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ customers: {+ Row: {+ id: string;+ stripe_customer_id: string | null;+ };+ Insert: {+ id: string;+ stripe_customer_id?: string | null;+ };+ Update: {+ id?: string;+ stripe_customer_id?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: 'customers_id_fkey';+ columns: ['id'];+ isOneToOne: true;+ referencedRelation: 'users';+ referencedColumns: ['id'];+ },+ ];+ };+ developer_errors: {+ Row: {+ api_key: string;+ host_env: Json | null;+ id: number;+ message: string | null;+ sdk_version: string | null;+ session_id: string | null;+ stack_trace: string | null;+ timestamp: string | null;+ type: string | null;+ };+ Insert: {+ api_key: string;+ host_env?: Json | null;+ id?: number;+ message?: string | null;+ sdk_version?: string | null;+ session_id?: string | null;+ stack_trace?: string | null;+ timestamp?: string | null;+ type?: string | null;+ };+ Update: {+ api_key?: string;+ host_env?: Json | null;+ id?: number;+ message?: string | null;+ sdk_version?: string | null;+ session_id?: string | null;+ stack_trace?: string | null;+ timestamp?: string | null;+ type?: string | null;+ };+ Relationships: [];+ };+ errors: {+ Row: {+ code: string | null;+ details: string | null;+ error_type: string | null;+ id: number;+ logs: string | null;+ session_id: string;+ timestamp: string;+ trigger_event_id: string | null;+ trigger_event_type: Database['public']['Enums']['trigger_event_type'] | null;+ };+ Insert: {+ code?: string | null;+ details?: string | null;+ error_type?: string | null;+ id?: number;+ logs?: string | null;+ session_id: string;+ timestamp: string;+ trigger_event_id?: string | null;+ trigger_event_type?: Database['public']['Enums']['trigger_event_type'] | null;+ };+ Update: {+ code?: string | null;+ details?: string | null;+ error_type?: string | null;+ id?: number;+ logs?: string | null;+ session_id?: string;+ timestamp?: string;+ trigger_event_id?: string | null;+ trigger_event_type?: Database['public']['Enums']['trigger_event_type'] | null;+ };+ Relationships: [+ {+ foreignKeyName: 'errors_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ llms: {+ Row: {+ agent_id: string | null;+ completion: Json | null;+ completion_tokens: number | null;+ cost: number | null;+ end_timestamp: string;+ id: string;+ init_timestamp: string;+ model: string | null;+ params: string | null;+ prompt: Json | null;+ prompt_tokens: number | null;+ promptarmor_flag: boolean | null;+ returns: string | null;+ session_id: string;+ thread_id: string | null;+ };+ Insert: {+ agent_id?: string | null;+ completion?: Json | null;+ completion_tokens?: number | null;+ cost?: number | null;+ end_timestamp: string;+ id?: string;+ init_timestamp: string;+ model?: string | null;+ params?: string | null;+ prompt?: Json | null;+ prompt_tokens?: number | null;+ promptarmor_flag?: boolean | null;+ returns?: string | null;+ session_id: string;+ thread_id?: string | null;+ };+ Update: {+ agent_id?: string | null;+ completion?: Json | null;+ completion_tokens?: number | null;+ cost?: number | null;+ end_timestamp?: string;+ id?: string;+ init_timestamp?: string;+ model?: string | null;+ params?: string | null;+ prompt?: Json | null;+ prompt_tokens?: number | null;+ promptarmor_flag?: boolean | null;+ returns?: string | null;+ session_id?: string;+ thread_id?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: 'llms_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ org_invites: {+ Row: {+ inviter_id: string;+ invitee_email: string;+ org_id: string;+ org_name: string;+ role: Database['public']['Enums']['org_roles'];+ inviter: string;+ created_at: string | null;+ };+ Insert: {+ inviter_id: string;+ invitee_email: string;+ org_id: string;+ org_name: string;+ role: Database['public']['Enums']['org_roles'];+ inviter: string;+ created_at?: string | null;+ };+ Update: {+ inviter_id?: string;+ invitee_email?: string;+ org_id?: string;+ org_name?: string;+ role?: Database['public']['Enums']['org_roles'];+ inviter?: string;+ created_at?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: 'org_invites_org_id_fkey';+ columns: ['org_id'];+ isOneToOne: false;+ referencedRelation: 'orgs';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'org_invites_inviter_id_fkey';+ columns: ['inviter_id'];+ isOneToOne: false;+ referencedRelation: 'users';+ referencedColumns: ['id'];+ },+ ];+ };+ orgs: {+ Row: {+ id: string;+ name: string;+ prem_status: Database['public']['Enums']['prem_status'];+ subscription_id: string | null;+ };+ Insert: {+ id?: string;+ name: string;+ prem_status?: Database['public']['Enums']['prem_status'];+ subscription_id?: string | null;+ };+ Update: {+ id?: string;+ name?: string;+ prem_status?: Database['public']['Enums']['prem_status'];+ subscription_id?: string | null;+ };+ Relationships: [];+ };+ prices: {+ Row: {+ active: boolean | null;+ currency: string | null;+ description: string | null;+ id: string;+ interval: Database['public']['Enums']['pricing_plan_interval'] | null;+ interval_count: number | null;+ metadata: Json | null;+ product_id: string | null;+ trial_period_days: number | null;+ type: Database['public']['Enums']['pricing_type'] | null;+ unit_amount: number | null;+ };+ Insert: {+ active?: boolean | null;+ currency?: string | null;+ description?: string | null;+ id: string;+ interval?: Database['public']['Enums']['pricing_plan_interval'] | null;+ interval_count?: number | null;+ metadata?: Json | null;+ product_id?: string | null;+ trial_period_days?: number | null;+ type?: Database['public']['Enums']['pricing_type'] | null;+ unit_amount?: number | null;+ };+ Update: {+ active?: boolean | null;+ currency?: string | null;+ description?: string | null;+ id?: string;+ interval?: Database['public']['Enums']['pricing_plan_interval'] | null;+ interval_count?: number | null;+ metadata?: Json | null;+ product_id?: string | null;+ trial_period_days?: number | null;+ type?: Database['public']['Enums']['pricing_type'] | null;+ unit_amount?: number | null;+ };+ Relationships: [+ {+ foreignKeyName: 'prices_product_id_fkey';+ columns: ['product_id'];+ isOneToOne: false;+ referencedRelation: 'products';+ referencedColumns: ['id'];+ },+ ];+ };+ products: {+ Row: {+ active: boolean | null;+ description: string | null;+ id: string;+ image: string | null;+ metadata: Json | null;+ name: string | null;+ };+ Insert: {+ active?: boolean | null;+ description?: string | null;+ id: string;+ image?: string | null;+ metadata?: Json | null;+ name?: string | null;+ };+ Update: {+ active?: boolean | null;+ description?: string | null;+ id?: string;+ image?: string | null;+ metadata?: Json | null;+ name?: string | null;+ };+ Relationships: [];+ };+ projects: {+ Row: {+ api_key: string;+ environment: Database['public']['Enums']['environment'];+ id: string;+ name: string;+ org_id: string;+ };+ Insert: {+ api_key?: string;+ environment?: Database['public']['Enums']['environment'];+ id?: string;+ name: string;+ org_id: string;+ };+ Update: {+ api_key?: string;+ environment?: Database['public']['Enums']['environment'];+ id?: string;+ name?: string;+ org_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'projects_org_id_fkey';+ columns: ['org_id'];+ isOneToOne: false;+ referencedRelation: 'orgs';+ referencedColumns: ['id'];+ },+ ];+ };+ sessions: {+ Row: {+ end_state: Database['public']['Enums']['end_state'] | null;+ end_state_reason: string | null;+ end_timestamp: string | null;+ host_env: Json | null;+ id: string;+ init_timestamp: string;+ project_id: string;+ project_id_secondary: string | null;+ tags: string | null;+ video: string | null;+ };+ Insert: {+ end_state?: Database['public']['Enums']['end_state'] | null;+ end_state_reason?: string | null;+ end_timestamp?: string | null;+ host_env?: Json | null;+ id: string;+ init_timestamp: string;+ project_id: string;+ project_id_secondary?: string | null;+ tags?: string | null;+ video?: string | null;+ };+ Update: {+ end_state?: Database['public']['Enums']['end_state'] | null;+ end_state_reason?: string | null;+ end_timestamp?: string | null;+ host_env?: Json | null;+ id?: string;+ init_timestamp?: string;+ project_id?: string;+ project_id_secondary?: string | null;+ tags?: string | null;+ video?: string | null;+ };+ Relationships: [+ {+ foreignKeyName: 'sessions_project_id_fkey';+ columns: ['project_id'];+ isOneToOne: false;+ referencedRelation: 'projects';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'sessions_project_id_secondary_fkey';+ columns: ['project_id_secondary'];+ isOneToOne: false;+ referencedRelation: 'projects';+ referencedColumns: ['id'];+ },+ ];+ };+ stats: {+ Row: {+ completion_tokens: number;+ cost: number | null;+ errors: number;+ events: number;+ prompt_tokens: number;+ session_id: string;+ };+ Insert: {+ completion_tokens?: number;+ cost?: number | null;+ errors?: number;+ events?: number;+ prompt_tokens?: number;+ session_id: string;+ };+ Update: {+ completion_tokens?: number;+ cost?: number | null;+ errors?: number;+ events?: number;+ prompt_tokens?: number;+ session_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'stats_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: true;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ subscriptions: {+ Row: {+ cancel_at: string | null;+ cancel_at_period_end: boolean | null;+ canceled_at: string | null;+ created: string;+ current_period_end: string;+ current_period_start: string;+ ended_at: string | null;+ id: string;+ metadata: Json | null;+ price_id: string | null;+ quantity: number | null;+ status: Database['public']['Enums']['subscription_status'] | null;+ trial_end: string | null;+ trial_start: string | null;+ user_id: string;+ };+ Insert: {+ cancel_at?: string | null;+ cancel_at_period_end?: boolean | null;+ canceled_at?: string | null;+ created?: string;+ current_period_end?: string;+ current_period_start?: string;+ ended_at?: string | null;+ id: string;+ metadata?: Json | null;+ price_id?: string | null;+ quantity?: number | null;+ status?: Database['public']['Enums']['subscription_status'] | null;+ trial_end?: string | null;+ trial_start?: string | null;+ user_id: string;+ };+ Update: {+ cancel_at?: string | null;+ cancel_at_period_end?: boolean | null;+ canceled_at?: string | null;+ created?: string;+ current_period_end?: string;+ current_period_start?: string;+ ended_at?: string | null;+ id?: string;+ metadata?: Json | null;+ price_id?: string | null;+ quantity?: number | null;+ status?: Database['public']['Enums']['subscription_status'] | null;+ trial_end?: string | null;+ trial_start?: string | null;+ user_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'subscriptions_price_id_fkey';+ columns: ['price_id'];+ isOneToOne: false;+ referencedRelation: 'prices';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'subscriptions_user_id_fkey';+ columns: ['user_id'];+ isOneToOne: false;+ referencedRelation: 'users';+ referencedColumns: ['id'];+ },+ ];+ };+ threads: {+ Row: {+ agent_id: string;+ id: string;+ session_id: string;+ };+ Insert: {+ agent_id: string;+ id: string;+ session_id: string;+ };+ Update: {+ agent_id?: string;+ id?: string;+ session_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'threads_agent_id_fkey';+ columns: ['agent_id'];+ isOneToOne: false;+ referencedRelation: 'agents';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'threads_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ tools: {+ Row: {+ agent_id: string;+ end_timestamp: string;+ id: string;+ init_timestamp: string;+ logs: string | null;+ name: string | null;+ params: string | null;+ returns: string | null;+ session_id: string;+ };+ Insert: {+ agent_id: string;+ end_timestamp: string;+ id?: string;+ init_timestamp: string;+ logs?: string | null;+ name?: string | null;+ params?: string | null;+ returns?: string | null;+ session_id: string;+ };+ Update: {+ agent_id?: string;+ end_timestamp?: string;+ id?: string;+ init_timestamp?: string;+ logs?: string | null;+ name?: string | null;+ params?: string | null;+ returns?: string | null;+ session_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'tools_agent_id_fkey';+ columns: ['agent_id'];+ isOneToOne: false;+ referencedRelation: 'agents';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'tools_session_id_fkey';+ columns: ['session_id'];+ isOneToOne: false;+ referencedRelation: 'sessions';+ referencedColumns: ['id'];+ },+ ];+ };+ ttd: {+ Row: {+ branch_name: string;+ completion: Json | null;+ completion_tokens: number | null;+ created_at: string;+ id: string;+ llm_id: string;+ model: string | null;+ params: string | null;+ prompt: Json | null;+ prompt_tokens: number | null;+ returns: string | null;+ session_id: string;+ ttd_id: string;+ };+ Insert: {+ branch_name?: string;+ completion?: Json | null;+ completion_tokens?: number | null;+ created_at?: string;+ id?: string;+ llm_id: string;+ model?: string | null;+ params?: string | null;+ prompt?: Json | null;+ prompt_tokens?: number | null;+ returns?: string | null;+ session_id: string;+ ttd_id: string;+ };+ Update: {+ branch_name?: string;+ completion?: Json | null;+ completion_tokens?: number | null;+ created_at?: string;+ id?: string;+ llm_id?: string;+ model?: string | null;+ params?: string | null;+ prompt?: Json | null;+ prompt_tokens?: number | null;+ returns?: string | null;+ session_id?: string;+ ttd_id?: string;+ };+ Relationships: [];+ };+ user_orgs: {+ Row: {+ org_id: string;+ role: Database['public']['Enums']['org_roles'];+ user_email: string | null;+ user_id: string;+ };+ Insert: {+ org_id: string;+ role?: Database['public']['Enums']['org_roles'];+ user_email?: string | null;+ user_id: string;+ };+ Update: {+ org_id?: string;+ role?: Database['public']['Enums']['org_roles'];+ user_email?: string | null;+ user_id?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'user_orgs_org_id_fkey';+ columns: ['org_id'];+ isOneToOne: false;+ referencedRelation: 'orgs';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'user_orgs_users_id_fkey';+ columns: ['user_id'];+ isOneToOne: false;+ referencedRelation: 'users';+ referencedColumns: ['id'];+ },+ ];+ };+ users: {+ Row: {+ avatar_url: string | null;+ billing_address: Json | null;+ full_name: string | null;+ id: string;+ payment_method: Json | null;+ email: string | null;+ survey_is_complete: boolean;+ };+ Insert: {+ avatar_url?: string | null;+ billing_address?: Json | null;+ full_name?: string | null;+ id: string;+ payment_method?: Json | null;+ email: string | null;+ survey_is_complete: boolean;+ };+ Update: {+ avatar_url?: string | null;+ billing_address?: Json | null;+ full_name?: string | null;+ id?: string;+ payment_method?: Json | null;+ email?: string | null;+ survey_is_complete: boolean;+ };+ Relationships: [+ {+ foreignKeyName: 'users_id_fkey';+ columns: ['id'];+ isOneToOne: true;+ referencedRelation: 'users';+ referencedColumns: ['id'];+ },+ ];+ };+ };+ Views: {+ [_ in never]: never;+ };+ Functions: {+ accept_org_invite: {+ Args: {+ org_id: string;+ };+ Returns: undefined;+ };+ create_new_org: {+ Args: {+ org_name: string;+ };+ Returns: string;+ };+ create_org_invite: {+ Args: {+ invited_email: string;+ org_id: string;+ role: Database['public']['Enums']['org_roles'];+ };+ Returns: undefined;+ };+ get_ttd: {+ Args: {+ ttd_id: string;+ };+ Returns: {+ branch_name: string;+ completion: Json | null;+ completion_tokens: number | null;+ created_at: string;+ id: string;+ llm_id: string;+ model: string | null;+ params: string | null;+ prompt: Json | null;+ prompt_tokens: number | null;+ returns: string | null;+ session_id: string;+ ttd_id: string;+ }[];+ };+ rename_org: {+ Args: {+ org_id: string;+ org_name: string;+ };+ Returns: undefined;+ };+ rotate_project_api_key: {+ Args: {+ project_id: string;+ };+ Returns: string;+ };+ transfer_org_ownership: {+ Args: {+ org_id: string;+ new_owner_id: string;+ };+ Returns: undefined;+ };+ user_aal: {+ Args: Record<PropertyKey, never>;+ Returns: string[];+ };+ user_belongs_to_org: {+ Args: {+ org_id: string;+ };+ Returns: boolean;+ };+ user_is_org_admin: {+ Args: {+ org_id: string;+ };+ Returns: boolean;+ };+ user_is_org_owner: {+ Args: {+ org_id: string;+ };+ Returns: boolean;+ };+ user_projects: {+ Args: Record<PropertyKey, never>;+ Returns: string[];+ };+ };+ Enums: {+ end_state: 'Success' | 'Fail' | 'Indeterminate';+ environment: 'production' | 'staging' | 'development' | 'community';+ org_roles: 'owner' | 'admin' | 'developer' | 'business_user';+ prem_status: 'free' | 'pro' | 'enterprise';+ pricing_plan_interval: 'day' | 'week' | 'month' | 'year';+ pricing_type: 'one_time' | 'recurring';+ subscription_status:+ | 'trialing'+ | 'active'+ | 'canceled'+ | 'incomplete'+ | 'incomplete_expired'+ | 'past_due'+ | 'unpaid'+ | 'paused';+ trigger_event_type: 'actions' | 'llms' | 'tools';+ };+ CompositeTypes: {+ [_ in never]: never;+ };+ };+};++type PublicSchema = Database[Extract<keyof Database, 'public'>];++export type Tables<+ PublicTableNameOrOptions extends+ | keyof (PublicSchema['Tables'] & PublicSchema['Views'])+ | { schema: keyof Database },+ TableName extends PublicTableNameOrOptions extends { schema: keyof Database }+ ? keyof (Database[PublicTableNameOrOptions['schema']]['Tables'] &+ Database[PublicTableNameOrOptions['schema']]['Views'])+ : never = never,+> = PublicTableNameOrOptions extends { schema: keyof Database }+ ? (Database[PublicTableNameOrOptions['schema']]['Tables'] &+ Database[PublicTableNameOrOptions['schema']]['Views'])[TableName] extends {+ Row: infer R;+ }+ ? R+ : never+ : PublicTableNameOrOptions extends keyof (PublicSchema['Tables'] & PublicSchema['Views'])+ ? (PublicSchema['Tables'] & PublicSchema['Views'])[PublicTableNameOrOptions] extends {+ Row: infer R;+ }+ ? R+ : never+ : never;++export type TablesInsert<+ PublicTableNameOrOptions extends keyof PublicSchema['Tables'] | { schema: keyof Database },+ TableName extends PublicTableNameOrOptions extends { schema: keyof Database }+ ? keyof Database[PublicTableNameOrOptions['schema']]['Tables']+ : never = never,+> = PublicTableNameOrOptions extends { schema: keyof Database }+ ? Database[PublicTableNameOrOptions['schema']]['Tables'][TableName] extends {+ Insert: infer I;+ }+ ? I+ : never+ : PublicTableNameOrOptions extends keyof PublicSchema['Tables']+ ? PublicSchema['Tables'][PublicTableNameOrOptions] extends {+ Insert: infer I;+ }+ ? I+ : never+ : never;++export type TablesUpdate<+ PublicTableNameOrOptions extends keyof PublicSchema['Tables'] | { schema: keyof Database },+ TableName extends PublicTableNameOrOptions extends { schema: keyof Database }+ ? keyof Database[PublicTableNameOrOptions['schema']]['Tables']+ : never = never,+> = PublicTableNameOrOptions extends { schema: keyof Database }+ ? Database[PublicTableNameOrOptions['schema']]['Tables'][TableName] extends {+ Update: infer U;+ }+ ? U+ : never+ : PublicTableNameOrOptions extends keyof PublicSchema['Tables']+ ? PublicSchema['Tables'][PublicTableNameOrOptions] extends {+ Update: infer U;+ }+ ? U+ : never+ : never;++export type Enums<+ PublicEnumNameOrOptions extends keyof PublicSchema['Enums'] | { schema: keyof Database },+ EnumName extends PublicEnumNameOrOptions extends { schema: keyof Database }+ ? keyof Database[PublicEnumNameOrOptions['schema']]['Enums']+ : never = never,+> = PublicEnumNameOrOptions extends { schema: keyof Database }+ ? Database[PublicEnumNameOrOptions['schema']]['Enums'][EnumName]+ : PublicEnumNameOrOptions extends keyof PublicSchema['Enums']+ ? PublicSchema['Enums'][PublicEnumNameOrOptions]+ : never;diff --git a/app/dashboard/lib/utils.tsx b/app/dashboard/lib/utils.tsxnew file mode 100644index 00000000..f7f6796e--- /dev/null+++ b/app/dashboard/lib/utils.tsx@@ -0,0 +1,178 @@+import { type DataPoint } from '@/components/charts/line-chart/chart';+import { type ClassValue, clsx } from 'clsx';+import { twMerge } from 'tailwind-merge';+import {+ formatNumber,+ formatPrice,+ formatMetric,+ formatPercentage,+} from './number_formatting_utils';++import { DateRange } from 'react-day-picker';+import { isWithinInterval } from 'date-fns';++export function cn(...inputs: ClassValue[]) {+ return twMerge(clsx(inputs));+}++export function truncateString(str: string | null, maxLength?: number) {+ if (!str) return '';+ if (!maxLength || str.length <= maxLength) {+ return str;+ }+ return str.substring(0, maxLength) + '...';+}++export function titleCase(str: string) {+ return str+ .split(' ')+ .map((word) =>+ word+ .split('-')+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())+ .join('-'),+ )+ .join(' ');+}++export function parseTags(input: string | null | undefined): string[] {+ if (!input) {+ return [];+ }++ try {+ const tags = JSON.parse(input);++ if (Array.isArray(tags) && tags.every((item) => typeof item === 'string')) {+ return tags;+ }+ } catch (error) {+ console.error('Failed to parse tags:', error);+ }++ return [];+}++export function formatTime(time: number): string {+ // Input is now expected to be in milliseconds+ const timeInMs = time;++ if (timeInMs < 1000) {+ return `${timeInMs.toFixed(2)}ms`;+ } else if (timeInMs < 60000) {+ return `${(timeInMs / 1000).toFixed(2)}s`;+ } else {+ const totalSeconds = Math.floor(timeInMs / 1000);+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ if (hours > 0) {+ return `${hours.toString().padStart(2, '0')}h ${minutes.toString().padStart(2, '0')}m ${seconds.toString().padStart(2, '0')}s`;+ }+ if (minutes > 0) {+ return `${minutes.toString().padStart(2, '0')}m ${seconds.toString().padStart(2, '0')}s`;+ } else {+ return `${seconds.toString().padStart(2, '0')}s`;+ }+ }+}++export function formatTimeRange(time: number, duration: number) {+ return `${Math.floor(time / 60)}m ${Math.floor(time % 60)}s - ${Math.floor(+ (time + duration) / 60,+ )}m ${Math.floor((time + duration) % 60)}s`;+}++export function formatDate(isoTime: string) {+ return new Date(isoTime).toLocaleString(undefined, {+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ });+}++export function sortDataIntoPresetIntervals(+ dataMax: number,+ numBuckets: number,+ bucketSizeOptions: number[],+ dataValues: number[],+ createName: (start: number, end: number) => string,+ dataPoints: DataPoint[],+ separateZeroBucket: boolean = false,+) {+ const rawBucketSize = dataMax / (numBuckets - 1);+ const bucketSize =+ bucketSizeOptions.find((size) => size >= rawBucketSize) ||+ bucketSizeOptions[bucketSizeOptions.length - 1];++ let currentStart = 0;+ while (currentStart < dataMax) {+ const bucketEnd = currentStart + bucketSize;+ dataPoints.push({+ name: createName(currentStart, bucketEnd),+ count: 0,+ });+ currentStart = bucketEnd;+ }++ dataValues.forEach((value) => {+ if (value === 0 && separateZeroBucket) {+ dataPoints[0].count++;+ } else {+ const bucketIndex = Math.min(+ Math.floor(value / bucketSize) + (separateZeroBucket ? 1 : 0),+ dataPoints.length - 1,+ );+ dataPoints[bucketIndex].count++;+ }+ });+}++export { formatNumber, formatPrice, formatMetric, formatPercentage };++export function filterByDateRange<T>(+ items: T[] | undefined | null,+ dateRange: DateRange | undefined,+ getTimestamp: (item: T) => string | Date,+): T[] {+ if (!items || !Array.isArray(items)) return [];+ if (!dateRange?.from || !dateRange?.to) return items;++ const start = dateRange.from;+ const end = dateRange.to;++ return items.filter((item) => {+ const timestamp = getTimestamp(item);+ const date = timestamp instanceof Date ? timestamp : new Date(timestamp);+ return isWithinInterval(date, { start, end });+ });+}++export function isSafariBrowser() {+ return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);+}++export const getDurationBar = (duration: number) => {+ // Define thresholds (in ms)+ const SHORT = 1000; // 1 second+ const MEDIUM = 5000; // 5 seconds++ // Calculate relative width (max 100px)+ const width = Math.min(Math.max(duration / 100, 10), 100);++ const color =+ duration <= SHORT ? 'bg-green-500' : duration <= MEDIUM ? 'bg-blue-500' : 'bg-red-500';++ return (+ <div className="flex items-center gap-2">+ <div className="h-2 rounded" style={{ width: width + 'px' }}>+ <div className={cn('h-full rounded', color)} style={{ width: '100%' }} />+ </div>+ <span className="text-xs"> {formatTime(duration)} </span>+ </div>+ );+};\ No newline at end of filediff --git a/app/dashboard/lib/utils/helpers.ts b/app/dashboard/lib/utils/helpers.tsnew file mode 100644index 00000000..4fa6dc94--- /dev/null+++ b/app/dashboard/lib/utils/helpers.ts@@ -0,0 +1,46 @@++export const getURL = () => {+ let url =+ process?.env?.NEXT_PUBLIC_SITE_URL ?? // Set this to your site URL in production env.+ process?.env?.NEXT_PUBLIC_VERCEL_URL ?? // Automatically set by Vercel.+ 'http://localhost:3000/';+ // Make sure to include `https://` when not localhost.+ url = url.includes('http') ? url : `https://${url}`;+ // Make sure to including trailing `/`.+ url = url.charAt(url.length - 1) === '/' ? url : `${url}/`;+ return url;+};++export const getAPIURL = () => {+ let url =+ process?.env?.NEXT_PUBLIC_API_URL ??+ process?.env?.NEXT_PUBLIC_VERCEL_URL ??+ 'http://localhost:8000/';+ // Make sure to include `https://` when not localhost.+ url = url.includes('http') ? url : `https://${url}`;+ // Make sure to including trailing `/`.+ url = url.charAt(url.length - 1) === '/' ? url : `${url}/`;+ return url;+}++export async function postData(url = '', data = {}) {+ const res = await fetch(url, {+ method: 'POST',+ headers: new Headers({ 'Content-Type': 'application/json' }),+ credentials: 'same-origin',+ body: JSON.stringify(data),+ });++ if (!res.ok) {+ console.error('Error in postData for URL:', url, 'Error:', res.statusText);+ return Promise.reject(res.statusText);+ }++ return res.json();+}++export const toDateTime = (secs: number) => {+ const t = new Date('1970-01-01T00:30:00Z'); // Unix epoch start.+ t.setSeconds(secs);+ return t;+};