Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix: Cross-platform port detection using find-process
trohitg0d33b16e6a42
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsxindex a4457c65..eff07e17 100644--- a/client/src/components/CredentialsModal.tsx+++ b/client/src/components/CredentialsModal.tsx@@ -16,7 +16,7 @@ import {import Modal from './ui/Modal';import QRCodeDisplay from './ui/QRCodeDisplay';import ApiKeyInput from './ui/ApiKeyInput';-import { useApiKeys, ProviderDefaults, ProviderUsageSummary } from '../hooks/useApiKeys';+import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary } from '../hooks/useApiKeys';import { useAppTheme } from '../hooks/useAppTheme';import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';import { useWhatsApp } from '../hooks/useWhatsApp';@@ -122,7 +122,7 @@ interface Props {const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {const theme = useAppTheme();- const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, getProviderDefaults, saveProviderDefaults, getProviderUsageSummary, isConnected } = useApiKeys();+ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, validateGoogleMapsKey, getProviderDefaults, saveProviderDefaults, getProviderUsageSummary, getAPIUsageSummary, isConnected } = useApiKeys();const whatsappStatus = useWhatsAppStatus();const androidStatus = useAndroidStatus();const twitterStatus = useTwitterStatus();@@ -152,11 +152,15 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {const [defaultsLoading, setDefaultsLoading] = useState<Record<string, boolean>>({});const [defaultsDirty, setDefaultsDirty] = useState<Record<string, boolean>>({});- // Usage & Costs state+ // Usage & Costs state (LLM providers)const [usageSummary, setUsageSummary] = useState<ProviderUsageSummary[]>([]);const [usageLoading, setUsageLoading] = useState(false);const [usageExpanded, setUsageExpanded] = useState(false);+ // Twitter API usage state+ const [twitterUsage, setTwitterUsage] = useState<APIUsageSummary | null>(null);+ const [twitterUsageLoading, setTwitterUsageLoading] = useState(false);+// Load stored keys and proxy URLsconst loadKeys = useCallback(async () => {const allItems = CATEGORIES.flatMap(c => c.items);@@ -253,6 +257,27 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {}}, [usageExpanded, isConnected, loadUsageSummary]);+ // Load Twitter API usage when Twitter panel is selected+ const loadTwitterUsage = useCallback(async () => {+ if (!isConnected) return;+ setTwitterUsageLoading(true);+ try {+ const services = await getAPIUsageSummary('twitter');+ const twitter = services.find(s => s.service === 'twitter') || null;+ setTwitterUsage(twitter);+ } catch (error) {+ console.warn('Error loading Twitter usage:', error);+ } finally {+ setTwitterUsageLoading(false);+ }+ }, [getAPIUsageSummary, isConnected]);++ useEffect(() => {+ if (selectedItem?.panelType === 'twitter' && isConnected) {+ loadTwitterUsage();+ }+ }, [selectedItem, isConnected, loadTwitterUsage]);+const handleValidate = async (id: string) => {const key = keys[id];if (!key?.trim()) return;@@ -1322,6 +1347,112 @@ const CredentialsModal: React.FC<Props> = ({ visible, onClose }) => {<Alert type="error" message={twitterError} showIcon style={{ marginBottom: theme.spacing.lg }} />)}+ {/* API Usage Stats */}+ <Collapse+ style={{ marginBottom: theme.spacing.lg, background: 'transparent' }}+ items={[{+ key: 'twitter-usage',+ label: (+ <Space>+ <DollarOutlined style={{ color: theme.dracula.yellow }} />+ <span>API Usage & Costs</span>+ {twitterUsage && (+ <Tag style={{+ backgroundColor: `${theme.dracula.green}25`,+ borderColor: `${theme.dracula.green}60`,+ color: theme.dracula.green,+ }}>+ ${twitterUsage.total_cost.toFixed(4)}+ </Tag>+ )}+ </Space>+ ),+ children: twitterUsageLoading ? (+ <div style={{ textAlign: 'center', padding: 16 }}><Spin size="small" /></div>+ ) : twitterUsage ? (+ <div>+ {/* Summary stats */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',+ gap: theme.spacing.md,+ marginBottom: theme.spacing.md,+ }}>+ <Statistic+ title="Total Cost"+ value={twitterUsage.total_cost}+ precision={4}+ prefix="$"+ valueStyle={{ color: theme.dracula.green, fontSize: 18 }}+ />+ <Statistic+ title="API Calls"+ value={twitterUsage.execution_count}+ valueStyle={{ color: theme.dracula.cyan, fontSize: 18 }}+ />+ <Statistic+ title="Resources"+ value={twitterUsage.total_resources}+ valueStyle={{ color: theme.dracula.purple, fontSize: 18 }}+ />+ </div>+ {/* Operations breakdown */}+ {twitterUsage.operations && twitterUsage.operations.length > 0 && (+ <div style={{+ borderTop: `1px solid ${theme.colors.border}`,+ paddingTop: theme.spacing.md,+ }}>+ <div style={{+ fontSize: theme.fontSize.xs,+ color: theme.colors.textSecondary,+ marginBottom: theme.spacing.sm,+ }}>+ Operations Breakdown+ </div>+ {twitterUsage.operations.map(op => (+ <div+ key={op.operation}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ padding: '4px 0',+ borderBottom: `1px solid ${theme.colors.border}`,+ }}+ >+ <span style={{ fontFamily: 'monospace', fontSize: 12 }}>{op.operation}</span>+ <Space size="small">+ <Tag style={{ margin: 0 }}>{op.resource_count} resources</Tag>+ <Tag style={{+ margin: 0,+ backgroundColor: `${theme.dracula.green}15`,+ color: theme.dracula.green,+ border: 'none',+ }}>+ ${op.total_cost.toFixed(4)}+ </Tag>+ </Space>+ </div>+ ))}+ </div>+ )}+ <Button+ size="small"+ icon={<ReloadOutlined />}+ onClick={loadTwitterUsage}+ style={{ marginTop: theme.spacing.md }}+ >+ Refresh+ </Button>+ </div>+ ) : (+ <div style={{ color: theme.colors.textSecondary, textAlign: 'center', padding: 16 }}>+ No usage data yet. Use Twitter nodes in your workflows to track costs.+ </div>+ ),+ }]}+ />+{/* Info box */}<div style={{padding: theme.spacing.md,diff --git a/client/src/components/PricingConfigModal.tsx b/client/src/components/PricingConfigModal.tsxnew file mode 100644index 00000000..357377fa--- /dev/null+++ b/client/src/components/PricingConfigModal.tsx@@ -0,0 +1,439 @@+/**+ * PricingConfigModal - View and edit pricing configuration+ * Displays LLM and API pricing in a tree view with inline editing+ */++import React, { useState, useEffect, useCallback } from 'react';+import { Button, Tabs, InputNumber, Collapse, Spin, message } from 'antd';+import {+ SaveOutlined,+ ReloadOutlined,+ DollarOutlined,+} from '@ant-design/icons';+import Modal from './ui/Modal';+import { usePricing, PricingConfig, LLMPricing } from '../hooks/usePricing';+import { useAppTheme } from '../hooks/useAppTheme';++// ============================================================================+// TYPES+// ============================================================================++interface Props {+ visible: boolean;+ onClose: () => void;+}++// ============================================================================+// HELPER COMPONENTS+// ============================================================================++interface LLMModelRowProps {+ model: string;+ pricing: LLMPricing;+ onChange: (field: keyof LLMPricing, value: number) => void;+ theme: ReturnType<typeof useAppTheme>;+}++const LLMModelRow: React.FC<LLMModelRowProps> = ({ model, pricing, onChange, theme }) => (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ padding: '8px 12px',+ borderBottom: `1px solid ${theme.colors.border}`,+ backgroundColor: model === '_default' ? `${theme.dracula.purple}15` : 'transparent',+ }}>+ <div style={{+ flex: 1,+ fontFamily: 'monospace',+ fontSize: 13,+ color: model === '_default' ? theme.dracula.purple : theme.colors.text,+ }}>+ {model === '_default' ? 'Default' : model}+ </div>+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ <span style={{ fontSize: 11, color: theme.colors.textSecondary }}>Input:</span>+ <InputNumber+ size="small"+ min={0}+ step={0.01}+ value={pricing.input}+ onChange={(v) => onChange('input', v ?? 0)}+ style={{ width: 80 }}+ prefix="$"+ />+ <span style={{ fontSize: 11, color: theme.colors.textSecondary }}>Output:</span>+ <InputNumber+ size="small"+ min={0}+ step={0.01}+ value={pricing.output}+ onChange={(v) => onChange('output', v ?? 0)}+ style={{ width: 80 }}+ prefix="$"+ />+ {pricing.cache_read !== undefined && (+ <>+ <span style={{ fontSize: 11, color: theme.colors.textSecondary }}>Cache:</span>+ <InputNumber+ size="small"+ min={0}+ step={0.01}+ value={pricing.cache_read}+ onChange={(v) => onChange('cache_read', v ?? 0)}+ style={{ width: 70 }}+ prefix="$"+ />+ </>+ )}+ {pricing.reasoning !== undefined && (+ <>+ <span style={{ fontSize: 11, color: theme.colors.textSecondary }}>Reasoning:</span>+ <InputNumber+ size="small"+ min={0}+ step={0.01}+ value={pricing.reasoning}+ onChange={(v) => onChange('reasoning', v ?? 0)}+ style={{ width: 80 }}+ prefix="$"+ />+ </>+ )}+ </div>+ </div>+);++interface APIPricingRowProps {+ operation: string;+ price: number;+ onChange: (value: number) => void;+ theme: ReturnType<typeof useAppTheme>;+}++const APIPricingRow: React.FC<APIPricingRowProps> = ({ operation, price, onChange, theme }) => {+ // Skip metadata keys+ if (operation.startsWith('_')) return null;++ return (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '8px 12px',+ borderBottom: `1px solid ${theme.colors.border}`,+ }}>+ <div style={{+ fontFamily: 'monospace',+ fontSize: 13,+ color: theme.colors.text,+ }}>+ {operation}+ </div>+ <InputNumber+ size="small"+ min={0}+ step={0.001}+ value={price}+ onChange={(v) => onChange(v ?? 0)}+ style={{ width: 100 }}+ prefix="$"+ />+ </div>+ );+};++// ============================================================================+// MAIN COMPONENT+// ============================================================================++const PricingConfigModal: React.FC<Props> = ({ visible, onClose }) => {+ const theme = useAppTheme();+ const { getPricingConfig, savePricingConfig, isConnected } = usePricing();++ const [config, setConfig] = useState<PricingConfig | null>(null);+ const [loading, setLoading] = useState(false);+ const [saving, setSaving] = useState(false);+ const [isDirty, setIsDirty] = useState(false);++ // Load config on mount+ const loadConfig = useCallback(async () => {+ if (!isConnected) return;+ setLoading(true);+ try {+ const data = await getPricingConfig();+ setConfig(data);+ setIsDirty(false);+ } catch (error) {+ message.error('Failed to load pricing config');+ } finally {+ setLoading(false);+ }+ }, [getPricingConfig, isConnected]);++ useEffect(() => {+ if (visible) {+ loadConfig();+ }+ }, [visible, loadConfig]);++ // Save config+ const handleSave = useCallback(async () => {+ if (!config) return;+ setSaving(true);+ try {+ const success = await savePricingConfig(config);+ if (success) {+ message.success('Pricing config saved');+ setIsDirty(false);+ } else {+ message.error('Failed to save pricing config');+ }+ } catch (error) {+ message.error('Failed to save pricing config');+ } finally {+ setSaving(false);+ }+ }, [config, savePricingConfig]);++ // Update LLM pricing+ const updateLLMPricing = useCallback((+ provider: string,+ model: string,+ field: keyof LLMPricing,+ value: number+ ) => {+ if (!config) return;+ setConfig(prev => {+ if (!prev) return prev;+ const updated = { ...prev };+ if (!updated.llm[provider]) updated.llm[provider] = {};+ if (!updated.llm[provider][model]) {+ updated.llm[provider][model] = { input: 0, output: 0 };+ }+ (updated.llm[provider][model] as Record<string, number | undefined>)[field] = value;+ return updated;+ });+ setIsDirty(true);+ }, [config]);++ // Update API pricing+ const updateAPIPricing = useCallback((+ service: string,+ operation: string,+ value: number+ ) => {+ if (!config) return;+ setConfig(prev => {+ if (!prev) return prev;+ const updated = { ...prev };+ if (!updated.api[service]) updated.api[service] = {};+ (updated.api[service] as Record<string, number>)[operation] = value;+ return updated;+ });+ setIsDirty(true);+ }, [config]);++ // Render LLM tab+ const renderLLMTab = () => {+ if (!config?.llm) return null;++ const providers = Object.keys(config.llm).sort();++ return (+ <Collapse+ defaultActiveKey={providers.slice(0, 2)}+ style={{ background: 'transparent' }}+ >+ {providers.map(provider => {+ const models = config.llm[provider];+ const modelNames = Object.keys(models).sort((a, b) => {+ if (a === '_default') return 1;+ if (b === '_default') return -1;+ return a.localeCompare(b);+ });++ return (+ <Collapse.Panel+ key={provider}+ header={+ <span style={{ textTransform: 'capitalize', fontWeight: 500 }}>+ {provider}+ <span style={{ marginLeft: 8, fontSize: 12, color: theme.colors.textSecondary }}>+ ({modelNames.length} models)+ </span>+ </span>+ }+ >+ <div style={{ fontSize: 11, color: theme.colors.textSecondary, padding: '4px 12px' }}>+ Prices in USD per million tokens (MTok)+ </div>+ {modelNames.map(model => (+ <LLMModelRow+ key={model}+ model={model}+ pricing={models[model]}+ onChange={(field, value) => updateLLMPricing(provider, model, field, value)}+ theme={theme}+ />+ ))}+ </Collapse.Panel>+ );+ })}+ </Collapse>+ );+ };++ // Render API tab+ const renderAPITab = () => {+ if (!config?.api) return null;++ const services = Object.keys(config.api).sort();++ return (+ <Collapse+ defaultActiveKey={services}+ style={{ background: 'transparent' }}+ >+ {services.map(service => {+ const operations = config.api[service];+ const opNames = Object.keys(operations).filter(k => !k.startsWith('_')).sort();+ const description = (operations as Record<string, string | number>)._description as string | undefined;+ const source = (operations as Record<string, string | number>)._source as string | undefined;++ return (+ <Collapse.Panel+ key={service}+ header={+ <span style={{ textTransform: 'capitalize', fontWeight: 500 }}>+ {service}+ <span style={{ marginLeft: 8, fontSize: 12, color: theme.colors.textSecondary }}>+ ({opNames.length} operations)+ </span>+ </span>+ }+ >+ {description && (+ <div style={{ fontSize: 12, color: theme.colors.textSecondary, padding: '4px 12px 8px' }}>+ {description}+ {source && (+ <a+ href={source}+ target="_blank"+ rel="noopener noreferrer"+ style={{ marginLeft: 8, color: theme.dracula.cyan }}+ >+ Source+ </a>+ )}+ </div>+ )}+ <div style={{ fontSize: 11, color: theme.colors.textSecondary, padding: '0 12px 4px' }}>+ Prices in USD per resource/request+ </div>+ {opNames.map(operation => (+ <APIPricingRow+ key={operation}+ operation={operation}+ price={(operations as Record<string, number>)[operation]}+ onChange={(value) => updateAPIPricing(service, operation, value)}+ theme={theme}+ />+ ))}+ </Collapse.Panel>+ );+ })}+ </Collapse>+ );+ };++ return (+ <Modal+ isOpen={visible}+ onClose={onClose}+ title="Pricing Configuration"+ maxWidth="700px"+ maxHeight="85vh"+ headerActions={+ <div style={{ display: 'flex', gap: 8 }}>+ <Button+ size="small"+ icon={<ReloadOutlined />}+ onClick={loadConfig}+ loading={loading}+ >+ Reload+ </Button>+ <Button+ type="primary"+ size="small"+ icon={<SaveOutlined />}+ onClick={handleSave}+ loading={saving}+ disabled={!isDirty}+ style={{+ backgroundColor: isDirty ? theme.dracula.green : undefined,+ borderColor: isDirty ? theme.dracula.green : undefined,+ }}+ >+ Save+ </Button>+ </div>+ }+ >+ <div style={{ padding: 16 }}>+ {loading ? (+ <div style={{ textAlign: 'center', padding: 40 }}>+ <Spin size="large" />+ </div>+ ) : config ? (+ <>+ {/* Version info */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: 16,+ padding: '8px 12px',+ backgroundColor: theme.colors.backgroundPanel,+ borderRadius: theme.borderRadius.sm,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>+ <DollarOutlined style={{ color: theme.dracula.yellow }} />+ <span style={{ color: theme.colors.textSecondary }}>+ Version: <strong style={{ color: theme.colors.text }}>{config.version}</strong>+ </span>+ </div>+ <span style={{ fontSize: 12, color: theme.colors.textSecondary }}>+ Last updated: {config.last_updated}+ </span>+ </div>++ {/* Tabs */}+ <Tabs+ defaultActiveKey="llm"+ items={[+ {+ key: 'llm',+ label: 'LLM Pricing',+ children: renderLLMTab(),+ },+ {+ key: 'api',+ label: 'API Pricing',+ children: renderAPITab(),+ },+ ]}+ />+ </>+ ) : (+ <div style={{ textAlign: 'center', padding: 40, color: theme.colors.textSecondary }}>+ {isConnected ? 'Failed to load config' : 'Not connected'}+ </div>+ )}+ </div>+ </Modal>+ );+};++export default PricingConfigModal;diff --git a/client/src/hooks/useApiKeys.ts b/client/src/hooks/useApiKeys.tsindex c6867c73..5c917d40 100644--- a/client/src/hooks/useApiKeys.ts+++ b/client/src/hooks/useApiKeys.ts@@ -48,6 +48,22 @@ export interface ProviderUsageSummary {models: ModelUsageSummary[];}+// API Usage interfaces (for Twitter, Google Maps, etc.)+export interface APIOperationSummary {+ operation: string;+ resource_count: number;+ total_cost: number;+ execution_count: number;+}++export interface APIUsageSummary {+ service: string;+ total_resources: number;+ total_cost: number;+ execution_count: number;+ operations: APIOperationSummary[];+}+export interface UseApiKeysResult {// Validate and store API keyvalidateApiKey: (provider: string, apiKey: string) => Promise<ApiKeyValidationResult>;@@ -77,9 +93,12 @@ export interface UseApiKeysResult {getProviderDefaults: (provider: string) => Promise<ProviderDefaults>;saveProviderDefaults: (provider: string, defaults: ProviderDefaults) => Promise<boolean>;- // Provider usage summary+ // Provider usage summary (LLM tokens)getProviderUsageSummary: () => Promise<ProviderUsageSummary[]>;+ // API usage summary (Twitter, etc.)+ getAPIUsageSummary: (service?: string) => Promise<APIUsageSummary[]>;+// StateisValidating: boolean;validationError: string | null;@@ -309,7 +328,7 @@ export const useApiKeys = (): UseApiKeysResult => {}, [sendRequest, isConnected]);/**- * Get aggregated usage and cost summary by provider+ * Get aggregated usage and cost summary by provider (LLM tokens)*/const getProviderUsageSummary = useCallback(async (): Promise<ProviderUsageSummary[]> => {if (!isConnected) return [];@@ -323,6 +342,27 @@ export const useApiKeys = (): UseApiKeysResult => {}}, [sendRequest, isConnected]);+ /**+ * Get aggregated API usage and cost by service (Twitter, etc.)+ * Optionally filter by service name.+ */+ const getAPIUsageSummary = useCallback(async (+ service?: string+ ): Promise<APIUsageSummary[]> => {+ if (!isConnected) return [];++ try {+ const response = await sendRequest<{ success: boolean; services: APIUsageSummary[] }>(+ 'get_api_usage_summary',+ { service }+ );+ return response?.services || [];+ } catch (error) {+ console.warn('Error fetching API usage summary:', error);+ return [];+ }+ }, [sendRequest, isConnected]);+return {validateApiKey,saveApiKey,@@ -335,6 +375,7 @@ export const useApiKeys = (): UseApiKeysResult => {getProviderDefaults,saveProviderDefaults,getProviderUsageSummary,+ getAPIUsageSummary,isValidating,validationError,isConnecteddiff --git a/client/src/hooks/usePricing.ts b/client/src/hooks/usePricing.tsnew file mode 100644index 00000000..43c2c8fd--- /dev/null+++ b/client/src/hooks/usePricing.ts@@ -0,0 +1,134 @@+/**+ * Hook for managing pricing configuration and API usage data.+ * Provides access to pricing config (LLM and API pricing) and usage summaries.+ */++import { useCallback } from 'react';+import { useWebSocket } from '../contexts/WebSocketContext';++// ============================================================================+// Types+// ============================================================================++export interface LLMPricing {+ input: number;+ output: number;+ cache_read?: number;+ reasoning?: number;+}++export interface APIPricing {+ [operation: string]: number;+}++export interface PricingConfig {+ version: string;+ last_updated: string;+ llm: Record<string, Record<string, LLMPricing>>;+ api: Record<string, APIPricing>;+ operation_map: Record<string, Record<string, string>>;+}++export interface APIOperationSummary {+ operation: string;+ resource_count: number;+ total_cost: number;+ execution_count: number;+}++export interface APIUsageSummary {+ service: string;+ total_resources: number;+ total_cost: number;+ execution_count: number;+ operations: APIOperationSummary[];+}++// ============================================================================+// Hook+// ============================================================================++export const usePricing = () => {+ const { sendRequest, isConnected } = useWebSocket();++ /**+ * Get the full pricing configuration (LLM + API pricing).+ * Returns null if not connected or request fails.+ */+ const getPricingConfig = useCallback(async (): Promise<PricingConfig | null> => {+ if (!isConnected) return null;++ try {+ const response = await sendRequest<{ success: boolean; config: PricingConfig }>(+ 'get_pricing_config',+ {}+ );+ return response?.config || null;+ } catch (error) {+ console.error('[usePricing] Failed to get pricing config:', error);+ return null;+ }+ }, [sendRequest, isConnected]);++ /**+ * Save updated pricing configuration.+ * Returns true if saved successfully.+ */+ const savePricingConfig = useCallback(async (config: PricingConfig): Promise<boolean> => {+ if (!isConnected) return false;++ try {+ const response = await sendRequest<{ success: boolean }>(+ 'save_pricing_config',+ { config }+ );+ return response?.success || false;+ } catch (error) {+ console.error('[usePricing] Failed to save pricing config:', error);+ return false;+ }+ }, [sendRequest, isConnected]);++ /**+ * Get aggregated API usage summary.+ * Optionally filter by service (e.g., 'twitter').+ */+ const getAPIUsageSummary = useCallback(async (+ service?: string+ ): Promise<APIUsageSummary[]> => {+ if (!isConnected) return [];++ try {+ const response = await sendRequest<{ success: boolean; services: APIUsageSummary[] }>(+ 'get_api_usage_summary',+ { service }+ );+ return response?.services || [];+ } catch (error) {+ console.error('[usePricing] Failed to get API usage summary:', error);+ return [];+ }+ }, [sendRequest, isConnected]);++ /**+ * Get Twitter-specific usage summary.+ * Convenience method that calls getAPIUsageSummary with 'twitter' filter.+ */+ const getTwitterUsage = useCallback(async (): Promise<APIUsageSummary | null> => {+ const services = await getAPIUsageSummary('twitter');+ return services.find(s => s.service === 'twitter') || null;+ }, [getAPIUsageSummary]);++ return {+ // Config methods+ getPricingConfig,+ savePricingConfig,+ // Usage methods+ getAPIUsageSummary,+ getTwitterUsage,+ // State+ isConnected,+ };+};++export default usePricing;diff --git a/package-lock.json b/package-lock.jsonindex 41f0a48d..a5f6c11d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "machinaos",- "version": "0.0.14",+ "version": "0.0.22","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "machinaos",- "version": "0.0.14",+ "version": "0.0.22","hasInstallScript": true,"license": "MIT","workspaces": [@@ -15,8 +15,9 @@"dependencies": {"concurrently": "^9.2.1","cross-env": "^7.0.3",+ "find-process": "^1.4.11","rimraf": "^6.0.1",- "whatsapp-rpc": "^0.0.8"+ "whatsapp-rpc": "^0.0.10"},"bin": {"machinaos": "bin/cli.js"@@ -27,7 +28,7 @@},"client": {"name": "react-flow-client",- "version": "0.0.13",+ "version": "0.0.22","dependencies": {"@ant-design/icons": "^6.0.2","@eslint/js": "^9.33.0",@@ -5980,6 +5981,29 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/find-process": {+ "version": "1.4.11",+ "resolved": "https://registry.npmjs.org/find-process/-/find-process-1.4.11.tgz",+ "integrity": "sha512-mAOh9gGk9WZ4ip5UjV0o6Vb4SrfnAmtsFNzkMRH9HQiFXVQnDyQFrSHTK5UoG6E+KV+s+cIznbtwpfN41l2nFA==",+ "license": "MIT",+ "dependencies": {+ "chalk": "~4.1.2",+ "commander": "^12.1.0",+ "loglevel": "^1.9.2"+ },+ "bin": {+ "find-process": "bin/find-process.js"+ }+ },+ "node_modules/find-process/node_modules/commander": {+ "version": "12.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz",+ "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },"node_modules/find-root": {"version": "1.1.0","resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz",@@ -7084,6 +7108,19 @@"integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==","license": "MIT"},+ "node_modules/loglevel": {+ "version": "1.9.2",+ "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz",+ "integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6.0"+ },+ "funding": {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/loglevel"+ }+ },"node_modules/longest-streak": {"version": "3.1.0","resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",@@ -11369,9 +11406,9 @@}},"node_modules/whatsapp-rpc": {- "version": "0.0.8",- "resolved": "https://registry.npmjs.org/whatsapp-rpc/-/whatsapp-rpc-0.0.8.tgz",- "integrity": "sha512-G5iwmj3CC6zFLLdNUgbdtDiIlLpGN/GQ71HvqOWgAV+mWHEDiuCrHWjcdHEN5fLKP4siBBHvVv487b5dwcD9eA==",+ "version": "0.0.10",+ "resolved": "https://registry.npmjs.org/whatsapp-rpc/-/whatsapp-rpc-0.0.10.tgz",+ "integrity": "sha512-F7pfeYzmP5f0pyAng2Ej+Fmh0PmpOmd2Hp6Vr5eYQtTp9YBsUX2dp4RTURupVeFai6oUipCaNdqQ9u/jlmzKqg==","hasInstallScript": true,"license": "MIT","dependencies": {diff --git a/package.json b/package.jsonindex 9e4118aa..765a2d56 100644--- a/package.json+++ b/package.json@@ -99,9 +99,10 @@"preuninstall": "node scripts/preinstall.js"},"dependencies": {- "whatsapp-rpc": "^0.0.10","concurrently": "^9.2.1","cross-env": "^7.0.3",- "rimraf": "^6.0.1"+ "find-process": "^1.4.11",+ "rimraf": "^6.0.1",+ "whatsapp-rpc": "^0.0.10"}}diff --git a/scripts/start.js b/scripts/start.jsindex e966ab48..4404903e 100755--- a/scripts/start.js+++ b/scripts/start.js@@ -3,10 +3,11 @@* Cross-platform start script for MachinaOS services.* Works on: Windows, macOS, Linux, WSL, Git Bash*/-import { execSync, spawn } from 'child_process';+import { spawn } from 'child_process';import { readFileSync, existsSync, copyFileSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';+import findProcess from 'find-process';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');@@ -17,50 +18,21 @@ const args = process.argv.slice(2);const isDaemonMode = args.includes('--daemon');const skipWhatsApp = args.includes('--skip-whatsapp');-// ============================================================================-// Platform Detection-// ============================================================================+// Platform detectionconst isWindows = process.platform === 'win32';const isGitBash = isWindows && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));-const isMac = process.platform === 'darwin';-const useUnixCommands = !isWindows || isGitBash;function getPlatformName() {if (isGitBash) return 'Git Bash';if (isWindows) return 'Windows';- if (isMac) return 'macOS';+ if (process.platform === 'darwin') return 'macOS';return 'Linux';}-// ============================================================================// Utilities-// ============================================================================-const elapsed = () => `${((Date.now() - START_TIME) / 1000).toFixed(2)}s`;const log = (msg) => console.log(`[${elapsed()}] ${msg}`);--function exec(cmd, options = {}) {- try {- return execSync(cmd, {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- timeout: options.timeout || 10000,- cwd: ROOT,- ...options- }).trim();- } catch {- return '';- }-}--function sleep(ms) {- try {- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);- } catch {- const end = Date.now() + ms;- while (Date.now() < end) { /* spin */ }- }-}+const sleep = (ms) => new Promise(r => setTimeout(r, ms));function loadConfig() {const envPath = existsSync(resolve(ROOT, '.env'))@@ -87,180 +59,99 @@ function loadConfig() {};}-// ============================================================================-// Port Management-// ============================================================================--function getPidsOnPort(port) {- const pids = new Set();-- if (useUnixCommands) {- const output = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);- for (const pid of output.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- pids.add(pid.trim());- }- }- if (pids.size === 0 && !isMac && !isGitBash) {- const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);- for (const match of ssOutput.matchAll(/pid=(\d+)/g)) {- pids.add(match[1]);- }- }- } else {- const output = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);- for (const line of output.split('\n')) {- const parts = line.trim().split(/\s+/);- const pid = parts[parts.length - 1];- if (pid && /^\d+$/.test(pid) && pid !== '0') {- pids.add(pid);- }- }- }-- return Array.from(pids);-}+// Port Management using find-process (cross-platform)+async function freePort(port) {+ const procs = await findProcess('port', port);+ if (procs.length === 0) return { freed: true, pids: [] };-function killPid(pid) {- if (useUnixCommands) {- exec(`kill -15 ${pid} 2>/dev/null`);- sleep(100);- exec(`kill -9 ${pid} 2>/dev/null`);- } else {- // /T kills process tree (parent + children), needed for uvicorn --reload- exec(`taskkill /PID ${pid} /T /F 2>nul`);+ const pids = procs.map(p => p.pid);+ for (const pid of pids) {+ try { process.kill(pid, 'SIGTERM'); } catch {}}-}--function freePort(port) {- const pids = getPidsOnPort(port);- if (pids.length === 0) return true;+ await sleep(300);+ // Force kill if still runningfor (const pid of pids) {- killPid(pid);+ try { process.kill(pid, 'SIGKILL'); } catch {}}- sleep(500);+ await sleep(200);- return getPidsOnPort(port).length === 0;+ const remaining = await findProcess('port', port);+ return { freed: remaining.length === 0, pids };}-// ============================================================================// Main-// ============================================================================--// Check if build has been run (before anything else)-const rootNodeModules = resolve(ROOT, 'node_modules');-const pythonVenv = resolve(ROOT, 'server', '.venv');-if (!existsSync(rootNodeModules) || !existsSync(pythonVenv)) {- console.error('\nError: Project not built. Run "npm run build" first.\n');- process.exit(1);-}--const config = loadConfig();--// Ensure Python UTF-8 encoding-process.env.PYTHONUTF8 = '1';--console.log('\n=== MachinaOS Starting ===\n');-log(`Platform: ${getPlatformName()}`);-log(`Mode: ${isDaemonMode ? 'Daemon (Gunicorn)' : 'Development (uvicorn)'}`);-log(`Ports: ${config.ports.join(', ')}`);-log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);-log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);+async function main() {+ // Check if build has been run+ const rootNodeModules = resolve(ROOT, 'node_modules');+ const pythonVenv = resolve(ROOT, 'server', '.venv');+ if (!existsSync(rootNodeModules) || !existsSync(pythonVenv)) {+ console.error('\nError: Project not built. Run "npm run build" first.\n');+ process.exit(1);+ }-// Create .env if not exists-const envPath = resolve(ROOT, '.env');-const templatePath = resolve(ROOT, '.env.template');-if (!existsSync(envPath) && existsSync(templatePath)) {- copyFileSync(templatePath, envPath);- log('Created .env from template');-}+ const config = loadConfig();+ process.env.PYTHONUTF8 = '1';++ console.log('\n=== MachinaOS Starting ===\n');+ log(`Platform: ${getPlatformName()}`);+ log(`Mode: ${isDaemonMode ? 'Daemon (Gunicorn)' : 'Development (uvicorn)'}`);+ log(`Ports: ${config.ports.join(', ')}`);+ log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);+ log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);++ // Create .env if not exists+ const envPath = resolve(ROOT, '.env');+ const templatePath = resolve(ROOT, '.env.template');+ if (!existsSync(envPath) && existsSync(templatePath)) {+ copyFileSync(templatePath, envPath);+ log('Created .env from template');+ }-// Free ports-log('Freeing ports...');-let allFree = true;-for (const port of config.ports) {- const pids = getPidsOnPort(port);- if (pids.length > 0) {- const freed = freePort(port);- if (freed) {- log(` Port ${port}: Freed (killed PIDs: ${pids.join(', ')})`);+ // Free ports using find-process (cross-platform)+ log('Freeing ports...');+ for (const port of config.ports) {+ const result = await freePort(port);+ if (result.pids.length > 0) {+ log(` Port ${port}: ${result.freed ? 'Freed' : 'Warning - could not free'} (PIDs: ${result.pids.join(', ')})`);} else {- log(` Port ${port}: Warning - could not free`);- allFree = false;+ log(` Port ${port}: Already free`);}- } else {- log(` Port ${port}: Already free`);}-}--if (!allFree) {- log('Warning: Some ports could not be freed. Services may fail to start.');-}--// Start services-log('Starting services...');-log('Press Ctrl+C to stop (use npm run stop to kill all services)\n');-// Detect if we should run dev mode (vite) or production mode (static serve)-// Check for vite in both root (npm workspaces hoist here) and client node_modules-const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');-const hasVite = existsSync(resolve(ROOT, 'node_modules', 'vite'))- || existsSync(resolve(ROOT, 'client', 'node_modules', 'vite'));-const isProduction = existsSync(clientDist) && !hasVite;+ // Start services+ log('Starting services...');+ log('Press Ctrl+C to stop\n');-if (isProduction) {- log('Mode: Production (serving pre-built client)');-} else {- log('Mode: Development (running vite)');-}--// Build concurrently command based on config-const services = [];--// Client: use static server in production, vite in development-if (isProduction) {- // Use dedicated serve-client.js script- services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);-} else {- services.push('npm:client:start');-}--// Python backend: use gunicorn in daemon mode, uvicorn in development-services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');--// WhatsApp RPC service (required)-if (!skipWhatsApp) {- services.push('npm:whatsapp:api');-}+ const clientDist = resolve(ROOT, 'client', 'dist', 'index.html');+ const hasVite = existsSync(resolve(ROOT, 'node_modules', 'vite'))+ || existsSync(resolve(ROOT, 'client', 'node_modules', 'vite'));+ const isProduction = existsSync(clientDist) && !hasVite;+ log(`Mode: ${isProduction ? 'Production' : 'Development'}`);-if (config.temporalEnabled) {- services.push('npm:temporal:worker');+ const services = [];+ if (isProduction) {+ services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);+ } else {+ services.push('npm:client:start');+ }+ services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');+ if (!skipWhatsApp) services.push('npm:whatsapp:api');+ if (config.temporalEnabled) services.push('npm:temporal:worker');++ const proc = spawn('npx', ['concurrently', '--raw', '--kill-others-on-fail', ...services], {+ cwd: ROOT,+ stdio: 'inherit',+ shell: true,+ env: { ...process.env, FORCE_COLOR: '1' }+ });++ process.on('SIGINT', () => proc.kill('SIGINT'));+ process.on('SIGTERM', () => proc.kill('SIGTERM'));+ proc.on('close', (code) => {+ console.log('\nServices stopped.');+ process.exit(code || 0);+ });}-const concurrentlyArgs = [- '--raw',- '--kill-others-on-fail',- ...services-];--// Use spawn with shell:true for cross-platform compatibility-const proc = spawn('npx', ['concurrently', ...concurrentlyArgs], {- cwd: ROOT,- stdio: 'inherit',- shell: true,- env: { ...process.env, FORCE_COLOR: '1' }-});--// Handle Ctrl+C gracefully-process.on('SIGINT', () => {- proc.kill('SIGINT');-});-process.on('SIGTERM', () => {- proc.kill('SIGTERM');-});--proc.on('close', (code) => {- console.log('\nServices stopped.');- process.exit(code || 0);-});+main().catch(console.error);diff --git a/scripts/stop.js b/scripts/stop.jsindex c30c0281..789dbe2a 100755--- a/scripts/stop.js+++ b/scripts/stop.js@@ -1,67 +1,28 @@#!/usr/bin/env node/*** Cross-platform stop script for MachinaOS services.- * Works on: Windows, macOS, Linux, WSL, Git Bash- *- * Uses Node.js native APIs where possible, with platform-specific- * fallbacks for process management (no cross-platform alternative exists).+ * Uses find-process npm package for reliable cross-platform port detection.*/-import { execSync } from 'child_process';import { readFileSync, existsSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';+import findProcess from 'find-process';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');-// ============================================================================-// Platform Detection-// ============================================================================const isWindows = process.platform === 'win32';const isGitBash = isWindows && (process.env.MSYSTEM || process.env.SHELL?.includes('bash'));-const isMac = process.platform === 'darwin';--// Git Bash on Windows uses Unix commands-const useUnixCommands = !isWindows || isGitBash;function getPlatformName() {if (isGitBash) return 'Git Bash';if (isWindows) return 'Windows';- if (isMac) return 'macOS';+ if (process.platform === 'darwin') return 'macOS';return 'Linux';}-// ============================================================================-// Utilities-// ============================================================================--/** Execute command silently, return output or empty string */-function exec(cmd, options = {}) {- try {- return execSync(cmd, {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- timeout: options.timeout || 10000,- cwd: ROOT,- ...options- }).trim();- } catch {- return '';- }-}--/** Cross-platform sleep using Atomics (efficient, no busy wait) */-function sleep(ms) {- try {- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);- } catch {- // Fallback for older Node.js- const end = Date.now() + ms;- while (Date.now() < end) { /* spin */ }- }-}+const sleep = (ms) => new Promise(r => setTimeout(r, ms));-/** Load config from .env file */function loadConfig() {const envPath = existsSync(resolve(ROOT, '.env'))? resolve(ROOT, '.env')@@ -87,215 +48,76 @@ function loadConfig() {};}-// ============================================================================-// Process Management (platform-specific - no cross-platform alternative)-// ============================================================================+async function killPort(port) {+ const procs = await findProcess('port', port);+ if (procs.length === 0) return { killed: [], portFree: true };-/** Get PIDs listening on a port */-function getPidsOnPort(port) {- const pids = new Set();+ const pids = procs.map(p => p.pid);- if (useUnixCommands) {- // lsof (macOS/Linux/Git Bash)- const lsofOutput = exec(`lsof -ti:${port} -sTCP:LISTEN 2>/dev/null`);- for (const pid of lsofOutput.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- pids.add(pid.trim());- }- }- // ss fallback (Linux)- if (pids.size === 0 && !isMac && !isGitBash) {- const ssOutput = exec(`ss -tlnp 2>/dev/null | grep :${port}`);- for (const match of ssOutput.matchAll(/pid=(\d+)/g)) {- pids.add(match[1]);- }- }- } else {- // netstat (Windows native)- const output = exec(`netstat -ano | findstr :${port} | findstr LISTENING`);- for (const line of output.split('\n')) {- const parts = line.trim().split(/\s+/);- const pid = parts[parts.length - 1];- if (pid && /^\d+$/.test(pid) && pid !== '0') {- pids.add(pid);- }- }+ // SIGTERM first+ for (const pid of pids) {+ try { process.kill(pid, 'SIGTERM'); } catch {}}+ await sleep(300);- return Array.from(pids);-}--/** Get child PIDs recursively (Unix only - Windows uses /T flag in taskkill) */-function getChildPids(parentPid) {- const children = new Set();-- if (useUnixCommands) {- const output = exec(`pgrep -P ${parentPid} 2>/dev/null`);- for (const pid of output.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- children.add(pid.trim());- for (const grandchild of getChildPids(pid.trim())) {- children.add(grandchild);- }- }- }+ // SIGKILL for stubborn processes+ for (const pid of pids) {+ try { process.kill(pid, 'SIGKILL'); } catch {}}- // Windows: taskkill /T handles children automatically, no need for wmic+ await sleep(200);- return Array.from(children);+ const remaining = await findProcess('port', port);+ return { killed: pids, portFree: remaining.length === 0 };}-/** Check if process is running */-function isRunning(pid) {- if (useUnixCommands) {- return exec(`kill -0 ${pid} 2>&1 && echo running`).includes('running');- } else {- return exec(`tasklist /FI "PID eq ${pid}" 2>nul`).includes(pid);- }-}+async function killByPattern(pattern) {+ const procs = await findProcess('name', pattern);+ const pids = procs.map(p => p.pid);-/** Kill a single process */-function killPid(pid) {- if (useUnixCommands) {- exec(`kill -15 ${pid} 2>/dev/null`);- sleep(100);- exec(`kill -9 ${pid} 2>/dev/null`);- } else {- // /T kills process tree (parent + children), needed for uvicorn --reload- exec(`taskkill /PID ${pid} /T /F 2>nul`);+ for (const pid of pids) {+ try { process.kill(pid, 'SIGKILL'); } catch {}}+ return pids;}-/** Kill all processes on a port */-function killPort(port) {- const pids = getPidsOnPort(port);- if (pids.length === 0) {- return { killed: [], portFree: true };- }+async function main() {+ const config = loadConfig();- // Collect all PIDs including children- const allPids = new Set(pids);- for (const pid of pids) {- for (const child of getChildPids(pid)) {- allPids.add(child);- }- }+ console.log('Stopping MachinaOS services...\n');+ console.log(`Platform: ${getPlatformName()}`);+ console.log(`Ports: ${config.ports.join(', ')}`);+ console.log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}\n`);- // Kill all- for (const pid of allPids) {- killPid(pid);- }+ let allStopped = true;- sleep(500);+ for (const port of config.ports) {+ const result = await killPort(port);+ const status = result.portFree ? '[OK]' : '[!!]';+ const message = result.portFree+ ? (result.killed.length > 0 ? `Killed ${result.killed.length} process(es)` : 'Free')+ : 'Warning: Port still in use';- // Verify- const killed = [];- for (const pid of allPids) {- if (!isRunning(pid)) {- killed.push(pid);+ console.log(`${status} Port ${port}: ${message}`);+ if (result.killed.length > 0) {+ console.log(` PIDs: ${result.killed.join(', ')}`);}+ if (!result.portFree) allStopped = false;}- // Retry stubborn ones- const stillRunning = Array.from(allPids).filter(pid => isRunning(pid));- if (stillRunning.length > 0) {- for (const pid of stillRunning) {- if (useUnixCommands) {- exec(`kill -9 ${pid} 2>/dev/null`);- } else {- exec(`taskkill /PID ${pid} /T /F 2>nul`);- }- }- sleep(500);- for (const pid of stillRunning) {- if (!isRunning(pid)) {- killed.push(pid);- }+ if (config.temporalEnabled) {+ const temporalPids = await killByPattern('temporal');+ if (temporalPids.length > 0) {+ console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);}}- return {- killed,- portFree: getPidsOnPort(port).length === 0- };-}--/** Kill processes by command pattern */-function killByPattern(pattern, debug = false) {- const killed = [];-- if (useUnixCommands) {- const output = exec(`pgrep -f "${pattern}" 2>/dev/null`);- if (debug && output) console.log(` [DEBUG] pgrep output: ${output}`);- for (const pid of output.split('\n')) {- if (pid.trim() && /^\d+$/.test(pid.trim())) {- exec(`kill -9 ${pid.trim()} 2>/dev/null`);- killed.push(pid.trim());- }- }+ console.log('');+ if (allStopped) {+ console.log('All services stopped.');} else {- // Use PowerShell to find processes by command line (wmic is deprecated)- const searchPattern = pattern.replace('.*', '').replace(/\\/g, '\\\\');- const psCmd = `powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${searchPattern}*' } | Select-Object -ExpandProperty ProcessId"`;- const output = exec(psCmd);- if (debug && output) console.log(` [DEBUG] PowerShell output: ${output}`);-- for (const line of output.split('\n')) {- const pid = line.trim();- if (pid && /^\d+$/.test(pid)) {- exec(`taskkill /PID ${pid} /T /F 2>nul`);- killed.push(pid);- }- }- }-- return killed;-}--// ============================================================================-// Main-// ============================================================================--const config = loadConfig();--console.log('Stopping MachinaOS services...\n');-console.log(`Platform: ${getPlatformName()}`);-console.log(`Ports: ${config.ports.join(', ')}`);-console.log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}\n`);--let allStopped = true;--// Stop services on ports-for (const port of config.ports) {- const result = killPort(port);- const status = result.portFree ? '[OK]' : '[!!]';- const message = result.portFree- ? (result.killed.length > 0 ? `Killed ${result.killed.length} process(es)` : 'Free')- : 'Warning: Port still in use';-- console.log(`${status} Port ${port}: ${message}`);- if (result.killed.length > 0) {- console.log(` PIDs: ${result.killed.join(', ')}`);- }- if (!result.portFree) {- allStopped = false;+ console.log('Warning: Some ports may still be in use.');+ process.exit(1);}}-// Kill Temporal workers if enabled (must include project path)-if (config.temporalEnabled) {- const temporalPids = killByPattern(`${ROOT}.*temporal`);- if (temporalPids.length > 0) {- console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);- console.log(` PIDs: ${temporalPids.join(', ')}`);- }-}--console.log('');-if (allStopped) {- console.log('All services stopped.');-} else {- console.log('Warning: Some ports may still be in use.');- console.log('Try running the script again or manually kill the processes.');- process.exit(1);-}+main().catch(console.error);diff --git a/server/config/pricing.json b/server/config/pricing.jsonnew file mode 100644index 00000000..2d40ade1--- /dev/null+++ b/server/config/pricing.json@@ -0,0 +1,138 @@+{+ "version": "2026.02",+ "last_updated": "2026-02-20",++ "llm": {+ "openai": {+ "gpt-5.2": {"input": 1.75, "output": 14.00},+ "gpt-5.1": {"input": 1.25, "output": 10.00},+ "gpt-5": {"input": 1.25, "output": 10.00},+ "gpt-5-mini": {"input": 0.25, "output": 2.00},+ "gpt-5-nano": {"input": 0.05, "output": 0.40},+ "gpt-5-pro": {"input": 15.00, "output": 120.00},+ "o3": {"input": 2.00, "output": 8.00, "reasoning": 8.00},+ "o3-mini": {"input": 1.10, "output": 4.40, "reasoning": 4.40},+ "o3-pro": {"input": 20.00, "output": 80.00, "reasoning": 80.00},+ "o4-mini": {"input": 1.10, "output": 4.40, "reasoning": 4.40},+ "o1": {"input": 15.00, "output": 60.00, "reasoning": 60.00},+ "o1-mini": {"input": 1.10, "output": 4.40, "reasoning": 4.40},+ "gpt-4o": {"input": 2.50, "output": 10.00},+ "gpt-4o-mini": {"input": 0.15, "output": 0.60},+ "gpt-4.1": {"input": 2.00, "output": 8.00},+ "gpt-4.1-mini": {"input": 0.40, "output": 1.60},+ "gpt-4.1-nano": {"input": 0.10, "output": 0.40},+ "gpt-4-turbo": {"input": 10.00, "output": 30.00},+ "gpt-4": {"input": 30.00, "output": 60.00},+ "gpt-3.5-turbo": {"input": 0.50, "output": 1.50},+ "_default": {"input": 2.50, "output": 10.00}+ },+ "anthropic": {+ "claude-opus-4.6": {"input": 5.00, "output": 25.00, "cache_read": 0.50},+ "claude-opus-4.5": {"input": 5.00, "output": 25.00, "cache_read": 0.50},+ "claude-opus-4.1": {"input": 15.00, "output": 75.00, "cache_read": 1.50},+ "claude-opus-4": {"input": 15.00, "output": 75.00, "cache_read": 1.50},+ "claude-sonnet-4.6": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-sonnet-4.5": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-sonnet-4": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-haiku-4.5": {"input": 1.00, "output": 5.00, "cache_read": 0.10},+ "claude-3-opus": {"input": 15.00, "output": 75.00, "cache_read": 1.50},+ "claude-3-5-sonnet": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-3-sonnet": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-3-haiku": {"input": 0.25, "output": 1.25, "cache_read": 0.03},+ "claude-3.5-haiku": {"input": 0.80, "output": 4.00, "cache_read": 0.08},+ "claude-opus": {"input": 5.00, "output": 25.00, "cache_read": 0.50},+ "claude-sonnet": {"input": 3.00, "output": 15.00, "cache_read": 0.30},+ "claude-haiku": {"input": 1.00, "output": 5.00, "cache_read": 0.10},+ "_default": {"input": 3.00, "output": 15.00, "cache_read": 0.30}+ },+ "gemini": {+ "gemini-3-pro": {"input": 2.00, "output": 12.00},+ "gemini-3-flash": {"input": 0.50, "output": 3.00},+ "gemini-2.5-pro": {"input": 1.25, "output": 10.00},+ "gemini-2.5-flash": {"input": 0.30, "output": 2.50},+ "gemini-2.5-flash-lite": {"input": 0.10, "output": 0.40},+ "gemini-2.0-flash": {"input": 0.10, "output": 0.40},+ "gemini-2.0-flash-lite": {"input": 0.08, "output": 0.30},+ "gemini-1.5-pro": {"input": 1.25, "output": 5.00},+ "gemini-1.5-flash": {"input": 0.075, "output": 0.30},+ "gemini-pro": {"input": 0.50, "output": 1.50},+ "_default": {"input": 0.50, "output": 2.50}+ },+ "groq": {+ "llama-4-scout": {"input": 0.11, "output": 0.34},+ "llama-4-maverick": {"input": 0.20, "output": 0.60},+ "llama-3.3-70b": {"input": 0.59, "output": 0.79},+ "llama-3.1-70b": {"input": 0.59, "output": 0.79},+ "llama-3.1-8b": {"input": 0.05, "output": 0.08},+ "llama3-70b": {"input": 0.59, "output": 0.79},+ "llama3-8b": {"input": 0.05, "output": 0.08},+ "qwen3-32b": {"input": 0.29, "output": 0.59},+ "qwen-qwq-32b": {"input": 0.29, "output": 0.59},+ "mixtral-8x7b": {"input": 0.24, "output": 0.24},+ "gpt-oss-20b": {"input": 0.075, "output": 0.30},+ "gpt-oss-120b": {"input": 0.15, "output": 0.60},+ "_default": {"input": 0.29, "output": 0.59}+ },+ "cerebras": {+ "llama-3.1-8b": {"input": 0.10, "output": 0.10},+ "llama-3.1-70b": {"input": 0.60, "output": 0.60},+ "llama-3.1-405b": {"input": 6.00, "output": 12.00},+ "llama3.1-8b": {"input": 0.10, "output": 0.10},+ "llama3.1-70b": {"input": 0.60, "output": 0.60},+ "qwen-3-32b": {"input": 0.20, "output": 0.20},+ "_default": {"input": 0.60, "output": 0.60}+ },+ "openrouter": {+ "_default": {"input": 1.00, "output": 5.00}+ }+ },++ "api": {+ "twitter": {+ "_description": "X/Twitter Pay-Per-Use API pricing (per resource/request)",+ "_source": "https://developer.x.com/#pricing",+ "posts_read": 0.005,+ "user_read": 0.010,+ "dm_event_read": 0.010,+ "list_read": 0.005,+ "space_read": 0.005,+ "community_read": 0.005,+ "note_read": 0.005,+ "followers_read": 0.010,+ "following_read": 0.010,+ "media_read": 0.005,+ "analytics_read": 0.005,+ "trend_read": 0.010,+ "counts_recent": 0.005,+ "counts_all": 0.010,+ "content_create": 0.010,+ "dm_create": 0.015,+ "user_interaction_create": 0.015,+ "interaction_delete": 0.010,+ "content_manage": 0.005,+ "list_create": 0.010,+ "list_manage": 0.005,+ "bookmark": 0.005,+ "media_metadata": 0.005,+ "privacy_update": 0.010,+ "mute_delete": 0.005+ }+ },++ "operation_map": {+ "twitter": {+ "tweet": "content_create",+ "reply": "content_create",+ "retweet": "user_interaction_create",+ "like": "user_interaction_create",+ "unlike": "interaction_delete",+ "delete": "content_manage",+ "search": "posts_read",+ "me": "user_read",+ "by_username": "user_read",+ "by_id": "user_read",+ "followers": "followers_read",+ "following": "following_read"+ }+ }+}diff --git a/server/core/database.py b/server/core/database.pyindex 3c81fdad..28a18617 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -111,6 +111,29 @@ class Database:))logger.info(f"Added {col} column to session_token_states")+ # Create api_usage_metrics table if not exists+ await conn.execute(text("""+ CREATE TABLE IF NOT EXISTS api_usage_metrics (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,+ session_id TEXT NOT NULL,+ node_id TEXT NOT NULL,+ workflow_id TEXT,+ service TEXT NOT NULL,+ operation TEXT NOT NULL,+ endpoint TEXT NOT NULL,+ resource_count INTEGER DEFAULT 1,+ cost REAL DEFAULT 0.0+ )+ """))+ await conn.execute(text(+ "CREATE INDEX IF NOT EXISTS idx_api_usage_session ON api_usage_metrics(session_id)"+ ))+ await conn.execute(text(+ "CREATE INDEX IF NOT EXISTS idx_api_usage_service ON api_usage_metrics(service)"+ ))+ logger.info("Ensured api_usage_metrics table exists")+except Exception as e:logger.warning(f"Migration check failed (table may not exist yet): {e}")@@ -1734,6 +1757,106 @@ class Database:logger.error("Failed to get provider usage summary", error=str(e))return []+ # ============================================================================+ # API Usage Metrics (Twitter, Google Maps, etc.)+ # ============================================================================++ async def save_api_usage_metric(self, metric: Dict[str, Any]) -> bool:+ """Save an API usage metric record.++ Args:+ metric: Dict with session_id, node_id, service, operation, endpoint, resource_count, cost+ """+ try:+ from models.database import APIUsageMetric++ async with self.get_session() as session:+ entry = APIUsageMetric(+ session_id=metric.get("session_id", "default"),+ node_id=metric.get("node_id", ""),+ workflow_id=metric.get("workflow_id"),+ service=metric.get("service", ""),+ operation=metric.get("operation", ""),+ endpoint=metric.get("endpoint", ""),+ resource_count=metric.get("resource_count", 1),+ cost=metric.get("cost", 0.0)+ )+ session.add(entry)+ await session.commit()+ return True+ except Exception as e:+ logger.error("Failed to save API usage metric", error=str(e))+ return False++ async def get_api_usage_summary(self, service: str = None) -> List[Dict[str, Any]]:+ """Get aggregated API usage and cost by service.++ Args:+ service: Optional service name to filter (e.g., 'twitter')++ Returns a list of service summaries with:+ - service: Service name (twitter, google_maps, etc.)+ - total_resources: Sum of resources fetched/requests made+ - total_cost: Sum of costs (USD)+ - execution_count: Number of API calls+ - operations: Breakdown by operation (list of dicts)+ """+ try:+ from models.database import APIUsageMetric+ from sqlalchemy import func++ async with self.get_session() as session:+ # Build query with optional service filter+ query = select(+ APIUsageMetric.service,+ APIUsageMetric.operation,+ func.sum(APIUsageMetric.resource_count).label("resource_count"),+ func.sum(APIUsageMetric.cost).label("cost"),+ func.count().label("execution_count")+ ).group_by(APIUsageMetric.service, APIUsageMetric.operation)++ if service:+ query = query.where(APIUsageMetric.service == service)++ query = query.order_by(APIUsageMetric.service, APIUsageMetric.operation)+ result = await session.execute(query)+ rows = result.all()++ # Aggregate by service+ services: Dict[str, Dict] = {}+ for row in rows:+ svc = row.service or "unknown"+ if svc not in services:+ services[svc] = {+ "service": svc,+ "total_resources": 0,+ "total_cost": 0.0,+ "execution_count": 0,+ "operations": []+ }++ s = services[svc]+ s["total_resources"] += row.resource_count or 0+ s["total_cost"] += float(row.cost or 0)+ s["execution_count"] += row.execution_count or 0++ s["operations"].append({+ "operation": row.operation,+ "resource_count": row.resource_count or 0,+ "total_cost": round(float(row.cost or 0), 6),+ "execution_count": row.execution_count or 0+ })++ # Round service totals+ for s in services.values():+ s["total_cost"] = round(s["total_cost"], 6)++ return list(services.values())++ except Exception as e:+ logger.error("Failed to get API usage summary", error=str(e))+ return []+# ============================================================================# Session Token State# ============================================================================diff --git a/server/models/database.py b/server/models/database.pyindex 9567a18d..1b4afc69 100644--- a/server/models/database.py+++ b/server/models/database.py@@ -368,6 +368,32 @@ class SessionTokenState(SQLModel, table=True):cumulative_total_cost: float = Field(default=0.0)+class APIUsageMetric(SQLModel, table=True):+ """API service usage for cost tracking (Twitter, Google Maps, etc.)."""++ __tablename__ = "api_usage_metrics"++ id: Optional[int] = Field(default=None, primary_key=True)+ timestamp: datetime = Field(+ default_factory=lambda: datetime.now(timezone.utc),+ sa_column=Column(DateTime(timezone=True), server_default=func.now())+ )+ session_id: str = Field(index=True, max_length=255)+ node_id: str = Field(max_length=255)+ workflow_id: Optional[str] = Field(default=None, max_length=255)++ # Service identification+ service: str = Field(index=True, max_length=50) # twitter, google_maps, etc.+ operation: str = Field(max_length=100) # posts_read, content_create, etc.+ endpoint: str = Field(max_length=100) # Handler action (tweet, search, like)++ # Usage counts+ resource_count: int = Field(default=1)++ # Cost in USD+ cost: float = Field(default=0.0)++# =============================================================================# Agent Teams - Claude SDK Agent Teams Pattern# =============================================================================diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex 8f8a2db7..2d2ce064 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -2191,6 +2191,41 @@ async def handle_save_provider_defaults(data: Dict[str, Any], websocket: WebSockreturn {"success": success, "provider": provider}+# ============================================================================+# Pricing Config Handlers+# ============================================================================++@ws_handler()+async def handle_get_pricing_config(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get full pricing configuration for display/editing."""+ from services.pricing import get_pricing_service+ pricing = get_pricing_service()+ return {"success": True, "config": pricing.get_config()}+++@ws_handler()+async def handle_save_pricing_config(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Save updated pricing configuration."""+ from services.pricing import get_pricing_service++ config = data.get('config')+ if not config:+ return {"success": False, "error": "No config provided"}++ pricing = get_pricing_service()+ success = pricing.save_config(config)+ return {"success": success}+++@ws_handler()+async def handle_get_api_usage_summary(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Get aggregated API usage and cost by service (Twitter, etc.)."""+ database = container.database()+ service = data.get('service') # Optional filter by service+ services = await database.get_api_usage_summary(service)+ return {"success": True, "services": services}++# ============================================================================# Compaction Handlers# ============================================================================@@ -2504,6 +2539,11 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {# Provider Usage Summary"get_provider_usage_summary": handle_get_provider_usage_summary,+ # Pricing Config+ "get_pricing_config": handle_get_pricing_config,+ "save_pricing_config": handle_save_pricing_config,+ "get_api_usage_summary": handle_get_api_usage_summary,+# Agent Teams"create_team": handle_create_team,"get_team": handle_get_team,diff --git a/server/services/handlers/twitter.py b/server/services/handlers/twitter.pyindex e51c3a34..2fe57709 100644--- a/server/services/handlers/twitter.py+++ b/server/services/handlers/twitter.py@@ -5,10 +5,52 @@ from typing import Dict, Anyfrom xdk import Clientfrom core.logging import get_logger+from services.pricing import get_pricing_servicelogger = get_logger(__name__)+async def _track_twitter_usage(+ node_id: str,+ action: str,+ resource_count: int = 1,+ workflow_id: str = None,+ session_id: str = "default"+) -> Dict[str, float]:+ """Track Twitter API usage for cost calculation.++ Args:+ node_id: The node executing the Twitter action+ action: Action name (tweet, search, followers, etc.)+ resource_count: Number of resources fetched (for paginated results)+ workflow_id: Optional workflow context+ session_id: Session for aggregation++ Returns:+ Cost breakdown dict with operation, unit_cost, resource_count, total_cost+ """+ from core.container import container++ pricing = get_pricing_service()+ cost_data = pricing.calculate_api_cost('twitter', action, resource_count)++ # Save to database+ db = container.database()+ await db.save_api_usage_metric({+ 'session_id': session_id,+ 'node_id': node_id,+ 'workflow_id': workflow_id,+ 'service': 'twitter',+ 'operation': cost_data.get('operation', action),+ 'endpoint': action,+ 'resource_count': resource_count,+ 'cost': cost_data.get('total_cost', 0.0)+ })++ logger.debug(f"[Twitter] Tracked usage: {action} x{resource_count} = ${cost_data.get('total_cost', 0):.6f}")+ return cost_data++async def _get_twitter_client() -> Client:"""Get authenticated Twitter client from stored OAuth 2.0 credentials."""# Import inside function to avoid circular import@@ -41,6 +83,10 @@ async def handle_twitter_send(try:client = await _get_twitter_client()+ # Extract workflow context for tracking+ workflow_id = context.get('workflow_id')+ session_id = context.get('session_id', 'default')+match action:case 'tweet':text = parameters.get('text', '')@@ -49,6 +95,8 @@ async def handle_twitter_send(# XDK API: client.posts.create(body={"text": "..."})payload = {"text": text[:280]}result = client.posts.create(body=payload)+ # Track: content_create $0.010+ await _track_twitter_usage(node_id, 'tweet', 1, workflow_id, session_id)return _success(_format_response(result), "tweet_sent", start_time)case 'reply':@@ -62,6 +110,8 @@ async def handle_twitter_send("reply": {"in_reply_to_tweet_id": reply_to}}result = client.posts.create(body=payload)+ # Track: content_create $0.010+ await _track_twitter_usage(node_id, 'reply', 1, workflow_id, session_id)return _success(_format_response(result), "reply_sent", start_time)case 'retweet':@@ -72,6 +122,8 @@ async def handle_twitter_send(# XDK API: client.users.repost_post(user_id, body={"tweet_id": "..."})payload = {"tweet_id": tweet_id}result = client.users.repost_post(user_id, body=payload)+ # Track: user_interaction_create $0.015+ await _track_twitter_usage(node_id, 'retweet', 1, workflow_id, session_id)return _success(_format_response(result), "retweeted", start_time)case 'like':@@ -82,6 +134,8 @@ async def handle_twitter_send(# XDK API: client.users.like_post(user_id, body={"tweet_id": "..."})payload = {"tweet_id": tweet_id}result = client.users.like_post(user_id, body=payload)+ # Track: user_interaction_create $0.015+ await _track_twitter_usage(node_id, 'like', 1, workflow_id, session_id)return _success(_format_response(result), "liked", start_time)case 'unlike':@@ -91,6 +145,8 @@ async def handle_twitter_send(user_id = await _get_my_user_id(client)# XDK API: client.users.unlike_post(user_id, tweet_id=post_id)result = client.users.unlike_post(user_id, tweet_id=tweet_id)+ # Track: interaction_delete $0.010+ await _track_twitter_usage(node_id, 'unlike', 1, workflow_id, session_id)return _success(_format_response(result), "unliked", start_time)case 'delete':@@ -99,6 +155,8 @@ async def handle_twitter_send(raise ValueError("tweet_id is required")# XDK API: client.posts.delete(post_id)result = client.posts.delete(tweet_id)+ # Track: content_manage $0.005+ await _track_twitter_usage(node_id, 'delete', 1, workflow_id, session_id)return _success(_format_response(result), "deleted", start_time)case _:@@ -126,6 +184,10 @@ async def handle_twitter_search(if not query:raise ValueError("Search query is required")+ # Extract workflow context for tracking+ workflow_id = context.get('workflow_id')+ session_id = context.get('session_id', 'default')+tweets = []# XDK API: client.posts.search_recent(query=..., max_results=..., tweet_fields=[...])for page in client.posts.search_recent(@@ -137,6 +199,10 @@ async def handle_twitter_search(tweets.extend([_format_tweet(t) for t in page_data])break # Only first page+ # Track: posts_read $0.005 per tweet fetched+ if tweets:+ await _track_twitter_usage(node_id, 'search', len(tweets), workflow_id, session_id)+return {"success": True,"result": {"tweets": tweets, "count": len(tweets), "query": query},@@ -161,10 +227,16 @@ async def handle_twitter_user(try:client = await _get_twitter_client()+ # Extract workflow context for tracking+ workflow_id = context.get('workflow_id')+ session_id = context.get('session_id', 'default')+match operation:case 'me':# XDK API: client.users.get_me(user_fields=[...])result = client.users.get_me(user_fields=["created_at", "description"])+ # Track: user_read $0.010+ await _track_twitter_usage(node_id, 'me', 1, workflow_id, session_id)return _success(_format_user_data(result.data), "user", start_time)case 'by_username':@@ -179,6 +251,8 @@ async def handle_twitter_user(users = getattr(result, 'data', []) or []if not users:raise ValueError(f"User @{username} not found")+ # Track: user_read $0.010+ await _track_twitter_usage(node_id, 'by_username', 1, workflow_id, session_id)return _success(_format_user_data(users[0]), "user", start_time)case 'by_id':@@ -193,6 +267,8 @@ async def handle_twitter_user(users = getattr(result, 'data', []) or []if not users:raise ValueError(f"User ID {user_id} not found")+ # Track: user_read $0.010+ await _track_twitter_usage(node_id, 'by_id', 1, workflow_id, session_id)return _success(_format_user_data(users[0]), "user", start_time)case 'followers':@@ -210,6 +286,9 @@ async def handle_twitter_user(page_data = getattr(page, 'data', []) or []users.extend([_format_user_data(u) for u in page_data])break # Only first page+ # Track: followers_read $0.010 per user+ if users:+ await _track_twitter_usage(node_id, 'followers', len(users), workflow_id, session_id)return _success({"users": users, "count": len(users)}, "followers", start_time)case 'following':@@ -227,6 +306,9 @@ async def handle_twitter_user(page_data = getattr(page, 'data', []) or []users.extend([_format_user_data(u) for u in page_data])break # Only first page+ # Track: following_read $0.010 per user+ if users:+ await _track_twitter_usage(node_id, 'following', len(users), workflow_id, session_id)return _success({"users": users, "count": len(users)}, "following", start_time)case _:diff --git a/server/services/pricing.py b/server/services/pricing.pyindex ef6dc9ba..2a1e0b8d 100644--- a/server/services/pricing.py+++ b/server/services/pricing.py@@ -1,147 +1,121 @@-"""LLM pricing service for token cost calculation.+"""Unified pricing service for LLM tokens and API costs.-Provides cost calculation for all supported LLM providers based on official pricing.-Pricing is in USD per million tokens (MTok).+Provides cost calculation for:+- LLM providers (OpenAI, Anthropic, Gemini, Groq, Cerebras, OpenRouter)+- API services (Twitter/X, Google Maps, etc.)++Pricing is loaded from config/pricing.json for user editability.+LLM pricing is in USD per million tokens (MTok).+API pricing is per resource/request."""+import jsonfrom dataclasses import dataclass-from typing import Dict, Optional+from datetime import datetime+from pathlib import Path+from typing import Any, Dict, Optional+from core.logging import get_loggerlogger = get_logger(__name__)+# Path to pricing configuration file+CONFIG_PATH = Path(__file__).parent.parent / "config" / "pricing.json"+@dataclassclass ModelPricing:- """Pricing for a specific model."""+ """Pricing for a specific LLM model."""input_per_mtok: float # USD per 1M input tokensoutput_per_mtok: float # USD per 1M output tokenscache_read_per_mtok: Optional[float] = None # USD per 1M cache read tokens (Anthropic)reasoning_per_mtok: Optional[float] = None # USD per 1M reasoning tokens (OpenAI o-series)-# Official pricing as of February 2026-# Sources: openai.com/api/pricing, anthropic.com/pricing, ai.google.dev/pricing,-# groq.com/pricing, cerebras.ai/pricing-PRICING_REGISTRY: Dict[str, Dict[str, ModelPricing]] = {- 'openai': {- # GPT-5 series- 'gpt-5.2': ModelPricing(1.75, 14.00),- 'gpt-5.1': ModelPricing(1.25, 10.00),- 'gpt-5': ModelPricing(1.25, 10.00),- 'gpt-5-mini': ModelPricing(0.25, 2.00),- 'gpt-5-nano': ModelPricing(0.05, 0.40),- 'gpt-5-pro': ModelPricing(15.00, 120.00),- # O-series (reasoning models)- 'o3': ModelPricing(2.00, 8.00, reasoning_per_mtok=8.00),- 'o3-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),- 'o3-pro': ModelPricing(20.00, 80.00, reasoning_per_mtok=80.00),- 'o4-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),- 'o1': ModelPricing(15.00, 60.00, reasoning_per_mtok=60.00),- 'o1-mini': ModelPricing(1.10, 4.40, reasoning_per_mtok=4.40),- # GPT-4 series- 'gpt-4o': ModelPricing(2.50, 10.00),- 'gpt-4o-mini': ModelPricing(0.15, 0.60),- 'gpt-4.1': ModelPricing(2.00, 8.00),- 'gpt-4.1-mini': ModelPricing(0.40, 1.60),- 'gpt-4.1-nano': ModelPricing(0.10, 0.40),- 'gpt-4-turbo': ModelPricing(10.00, 30.00),- 'gpt-4': ModelPricing(30.00, 60.00),- # GPT-3.5- 'gpt-3.5-turbo': ModelPricing(0.50, 1.50),- # Default fallback- '_default': ModelPricing(2.50, 10.00),- },- 'anthropic': {- # Claude 4.x series- 'claude-opus-4.6': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),- 'claude-opus-4.5': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),- 'claude-opus-4.1': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),- 'claude-opus-4': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),- 'claude-sonnet-4.6': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-sonnet-4.5': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-sonnet-4': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-haiku-4.5': ModelPricing(1.00, 5.00, cache_read_per_mtok=0.10),- # Claude 3.x series (legacy)- 'claude-3-opus': ModelPricing(15.00, 75.00, cache_read_per_mtok=1.50),- 'claude-3-5-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-3-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-3-haiku': ModelPricing(0.25, 1.25, cache_read_per_mtok=0.03),- 'claude-3.5-haiku': ModelPricing(0.80, 4.00, cache_read_per_mtok=0.08),- # Partial matches (for model names like claude-3-5-sonnet-20241022)- 'claude-opus': ModelPricing(5.00, 25.00, cache_read_per_mtok=0.50),- 'claude-sonnet': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- 'claude-haiku': ModelPricing(1.00, 5.00, cache_read_per_mtok=0.10),- # Default fallback- '_default': ModelPricing(3.00, 15.00, cache_read_per_mtok=0.30),- },- 'gemini': {- # Gemini 3.x series- 'gemini-3-pro': ModelPricing(2.00, 12.00),- 'gemini-3-flash': ModelPricing(0.50, 3.00),- # Gemini 2.5 series- 'gemini-2.5-pro': ModelPricing(1.25, 10.00),- 'gemini-2.5-flash': ModelPricing(0.30, 2.50),- 'gemini-2.5-flash-lite': ModelPricing(0.10, 0.40),- # Gemini 2.0 series- 'gemini-2.0-flash': ModelPricing(0.10, 0.40),- 'gemini-2.0-flash-lite': ModelPricing(0.08, 0.30),- # Gemini 1.x series (legacy)- 'gemini-1.5-pro': ModelPricing(1.25, 5.00),- 'gemini-1.5-flash': ModelPricing(0.075, 0.30),- 'gemini-pro': ModelPricing(0.50, 1.50),- # Default fallback- '_default': ModelPricing(0.50, 2.50),- },- 'groq': {- # Llama 4 series- 'llama-4-scout': ModelPricing(0.11, 0.34),- 'llama-4-maverick': ModelPricing(0.20, 0.60),- # Llama 3.x series- 'llama-3.3-70b': ModelPricing(0.59, 0.79),- 'llama-3.1-70b': ModelPricing(0.59, 0.79),- 'llama-3.1-8b': ModelPricing(0.05, 0.08),- 'llama3-70b': ModelPricing(0.59, 0.79),- 'llama3-8b': ModelPricing(0.05, 0.08),- # Qwen series- 'qwen3-32b': ModelPricing(0.29, 0.59),- 'qwen-qwq-32b': ModelPricing(0.29, 0.59),- # Mixtral- 'mixtral-8x7b': ModelPricing(0.24, 0.24),- # GPT OSS- 'gpt-oss-20b': ModelPricing(0.075, 0.30),- 'gpt-oss-120b': ModelPricing(0.15, 0.60),- # Default fallback- '_default': ModelPricing(0.29, 0.59),- },- 'cerebras': {- # Llama series- 'llama-3.1-8b': ModelPricing(0.10, 0.10),- 'llama-3.1-70b': ModelPricing(0.60, 0.60),- 'llama-3.1-405b': ModelPricing(6.00, 12.00),- 'llama3.1-8b': ModelPricing(0.10, 0.10),- 'llama3.1-70b': ModelPricing(0.60, 0.60),- # Qwen- 'qwen-3-32b': ModelPricing(0.20, 0.20),- # Default fallback- '_default': ModelPricing(0.60, 0.60),- },- 'openrouter': {- # OpenRouter passes through provider pricing- # These are approximate defaults; actual cost depends on underlying provider- '_default': ModelPricing(1.00, 5.00),- },-}--class PricingService:- """Service for calculating LLM token costs."""+ """Unified service for calculating LLM token costs and API costs."""def __init__(self):- self._registry = PRICING_REGISTRY+ self._config: Dict[str, Any] = {}+ self._llm_registry: Dict[str, Dict[str, ModelPricing]] = {}+ self._load_config()++ def _load_config(self) -> None:+ """Load pricing config from JSON file."""+ if CONFIG_PATH.exists():+ try:+ with open(CONFIG_PATH, 'r', encoding='utf-8') as f:+ self._config = json.load(f)+ self._build_llm_registry()+ logger.info(f"[Pricing] Loaded pricing config v{self._config.get('version', 'unknown')}")+ except Exception as e:+ logger.error(f"[Pricing] Failed to load config: {e}")+ self._config = {"llm": {}, "api": {}, "operation_map": {}}+ self._llm_registry = {}+ else:+ logger.warning(f"[Pricing] Config not found: {CONFIG_PATH}")+ self._config = {"llm": {}, "api": {}, "operation_map": {}}+ self._llm_registry = {}++ def _build_llm_registry(self) -> None:+ """Build ModelPricing objects from JSON config."""+ self._llm_registry = {}+ llm_config = self._config.get("llm", {})++ for provider, models in llm_config.items():+ self._llm_registry[provider] = {}+ for model_name, pricing_data in models.items():+ if isinstance(pricing_data, dict):+ self._llm_registry[provider][model_name] = ModelPricing(+ input_per_mtok=pricing_data.get("input", 1.0),+ output_per_mtok=pricing_data.get("output", 5.0),+ cache_read_per_mtok=pricing_data.get("cache_read"),+ reasoning_per_mtok=pricing_data.get("reasoning"),+ )++ def reload(self) -> None:+ """Reload pricing config from disk (for live updates)."""+ self._load_config()++ def get_config(self) -> Dict[str, Any]:+ """Get full pricing config for frontend display/editing."""+ return self._config++ def save_config(self, config: Dict[str, Any]) -> bool:+ """Save updated pricing config to JSON file.++ Args:+ config: New pricing configuration dict++ Returns:+ True if saved successfully, False otherwise+ """+ try:+ # Update last_updated timestamp+ config["last_updated"] = datetime.utcnow().strftime("%Y-%m-%d")++ # Ensure config directory exists+ CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)++ with open(CONFIG_PATH, 'w', encoding='utf-8') as f:+ json.dump(config, f, indent=2)++ # Reload the config into memory+ self._config = config+ self._build_llm_registry()++ logger.info(f"[Pricing] Saved pricing config v{config.get('version', 'unknown')}")+ return True+ except Exception as e:+ logger.error(f"[Pricing] Failed to save config: {e}")+ return False++ # =========================================================================+ # LLM Token Pricing (existing functionality)+ # =========================================================================def get_pricing(self, provider: str, model: str) -> ModelPricing:- """Get pricing for a specific model.+ """Get pricing for a specific LLM model.Uses partial matching: 'claude-3-5-sonnet-20241022' matches 'claude-3-5-sonnet'.Falls back to '_default' if no match found.@@ -156,7 +130,7 @@ class PricingService:provider_lower = provider.lower()model_lower = model.lower() if model else ''- provider_pricing = self._registry.get(provider_lower, {})+ provider_pricing = self._llm_registry.get(provider_lower, {})# Try exact match firstif model_lower in provider_pricing:@@ -191,7 +165,7 @@ class PricingService:cache_creation_tokens: int = 0,reasoning_tokens: int = 0) -> Dict[str, float]:- """Calculate cost for token usage.+ """Calculate cost for LLM token usage.Args:provider: LLM provider name@@ -240,13 +214,13 @@ class PricingService:}def get_all_pricing(self) -> Dict[str, Dict[str, Dict[str, float]]]:- """Get all pricing data for frontend display.+ """Get all LLM pricing data for frontend display.Returns:Nested dict: {provider: {model: {input, output, cache_read, reasoning}}}"""result = {}- for provider, models in self._registry.items():+ for provider, models in self._llm_registry.items():result[provider] = {}for model, pricing in models.items():result[provider][model] = {@@ -257,6 +231,91 @@ class PricingService:}return result+ # =========================================================================+ # API Service Pricing (new functionality)+ # =========================================================================++ def get_api_price(self, service: str, operation: str) -> float:+ """Get price for an API operation.++ Args:+ service: Service name (e.g., 'twitter', 'google_maps')+ operation: Operation key (e.g., 'posts_read', 'content_create')++ Returns:+ USD cost per resource/request+ """+ api_config = self._config.get('api', {})+ service_config = api_config.get(service, {})+ return service_config.get(operation, 0.0)++ def get_api_pricing(self, service: str) -> Dict[str, float]:+ """Get all pricing for an API service.++ Args:+ service: Service name (e.g., 'twitter')++ Returns:+ Dict of {operation: price} for the service+ """+ api_config = self._config.get('api', {})+ service_config = api_config.get(service, {})+ # Filter out metadata keys starting with _+ return {k: v for k, v in service_config.items() if not k.startswith('_') and isinstance(v, (int, float))}++ def map_action_to_operation(self, service: str, action: str) -> Optional[str]:+ """Map handler action to pricing operation.++ Args:+ service: Service name (e.g., 'twitter')+ action: Handler action (e.g., 'tweet', 'search', 'like')++ Returns:+ Pricing operation key or None if no mapping+ """+ operation_map = self._config.get('operation_map', {})+ service_map = operation_map.get(service, {})+ return service_map.get(action)++ def calculate_api_cost(+ self,+ service: str,+ action: str,+ resource_count: int = 1+ ) -> Dict[str, Any]:+ """Calculate cost for API usage.++ Args:+ service: Service name (e.g., 'twitter')+ action: Handler action (e.g., 'tweet', 'search')+ resource_count: Number of resources fetched or requests made++ Returns:+ Dict with cost breakdown:+ - operation: Pricing operation key+ - unit_cost: USD per resource/request+ - resource_count: Number of resources+ - total_cost: Total USD cost+ """+ operation = self.map_action_to_operation(service, action)+ if not operation:+ return {+ 'operation': action,+ 'unit_cost': 0.0,+ 'resource_count': resource_count,+ 'total_cost': 0.0+ }++ unit_cost = self.get_api_price(service, operation)+ total_cost = unit_cost * resource_count++ return {+ 'operation': operation,+ 'unit_cost': unit_cost,+ 'resource_count': resource_count,+ 'total_cost': round(total_cost, 6)+ }+# Singleton instance_service: Optional[PricingService] = None