Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

node editor update:

tilakpatel22a2db6acf8b31
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 247dce402..16e72a49e 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1154,6 +1154,9 @@ target_precompile_headers(FinceptTerminal PRIVATE
<span>
)
+# ── OpenSSL (from vcpkg) — needed for Google Sheets JWT signing ───────────────
+set(VCPKG_OPENSSL "C:/windowsdisk/fincept-cpp/vcpkg_installed/x64-windows")
+target_include_directories(FinceptTerminal PRIVATE "${VCPKG_OPENSSL}/include")
target_link_libraries(FinceptTerminal PRIVATE
Qt6::Widgets
Qt6::Charts
@@ -1166,6 +1169,19 @@ target_link_libraries(FinceptTerminal PRIVATE
qgeoview
QSimpleUpdater
whisper
+ "${VCPKG_OPENSSL}/lib/libcrypto.lib"
+ "${VCPKG_OPENSSL}/lib/libssl.lib"
+)
+
+# Copy OpenSSL DLLs to build output
+add_custom_command(TARGET FinceptTerminal POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${VCPKG_OPENSSL}/bin/libcrypto-3-x64.dll"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/libcrypto-3-x64.dll"
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "${VCPKG_OPENSSL}/bin/libssl-3-x64.dll"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/libssl-3-x64.dll"
+ COMMENT "Copying OpenSSL DLLs..."
)
if(HAS_WEBSOCKETS)
@@ -1234,3 +1250,11 @@ if(WIN32)
)
endif()
endif()
+
+# ── Copy Python scripts to build output ──────────────────────────────────────
+add_custom_command(TARGET FinceptTerminal POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_directory
+ "${CMAKE_CURRENT_SOURCE_DIR}/scripts"
+ "$<TARGET_FILE_DIR:FinceptTerminal>/scripts"
+ COMMENT "Copying Python scripts to build output..."
+)
diff --git a/fincept-qt/resources/requirements-numpy1.txt b/fincept-qt/resources/requirements-numpy1.txt
index 5b0c0074c..f6a6a7e4f 100644
--- a/fincept-qt/resources/requirements-numpy1.txt
+++ b/fincept-qt/resources/requirements-numpy1.txt
@@ -5,6 +5,10 @@
numpy>=1.26.4,<2.0
pandas>=2.0.0,<2.3.0
+# Spreadsheet I/O (local xlsx/csv + Google Sheets)
+openpyxl>=3.1.0
+gspread>=6.0.0
+
# Backtesting and trading (NumPy 1.x dependent)
vectorbt==0.28.2
backtesting==0.6.5
diff --git a/fincept-qt/resources/requirements-numpy2.txt b/fincept-qt/resources/requirements-numpy2.txt
index a047e8d5b..7b53422e4 100644
--- a/fincept-qt/resources/requirements-numpy2.txt
+++ b/fincept-qt/resources/requirements-numpy2.txt
@@ -51,6 +51,10 @@ urllib3==2.5.0
yarl==1.22.0
zstandard==0.25.0
+# Spreadsheet I/O (local xlsx/csv + Google Sheets)
+openpyxl>=3.1.0
+gspread>=6.0.0
+
# SEC EDGAR data
edgartools>=5.6.0
diff --git a/fincept-qt/scripts/spreadsheet.py b/fincept-qt/scripts/spreadsheet.py
new file mode 100644
index 000000000..ee205045f
--- /dev/null
+++ b/fincept-qt/scripts/spreadsheet.py
@@ -0,0 +1,260 @@
+"""
+spreadsheet.py — unified local + Google Sheets I/O for the Fincept workflow node.
+
+Usage:
+ python spreadsheet.py --args '<json>'
+
+The JSON args object supports:
+ source : "local" | "google"
+ operation : "read" | "write" | "append" | "clear"
+ file_path : path to local .xlsx or .csv (source=local)
+ spreadsheet_id : Google Sheet ID from URL (source=google)
+ sheet_name : sheet/tab name (default "Sheet1")
+ range : cell range e.g. "A1:D100" (default "A1:Z1000")
+ credentials_path : path to service account credentials.json
+ leave empty for public sheets (source=google, read-only)
+ data : [[...], [...], ...] rows to write/append
+
+Outputs a single JSON object to stdout.
+"""
+
+import sys
+import json
+import argparse
+import os
+
+
+def parse_range(range_str):
+ """Parse 'A1:D100' -> (r1, c1, r2, c2) 1-based. Returns None on failure."""
+ try:
+ parts = range_str.upper().split(":")
+ if len(parts) != 2:
+ return None
+
+ def parse_cell(cell):
+ col = 0
+ i = 0
+ while i < len(cell) and cell[i].isalpha():
+ col = col * 26 + (ord(cell[i]) - ord("A") + 1)
+ i += 1
+ row = int(cell[i:])
+ return row, col
+
+ r1, c1 = parse_cell(parts[0].strip())
+ r2, c2 = parse_cell(parts[1].strip())
+ return r1, c1, r2, c2
+ except Exception:
+ return None
+
+
+# ── LOCAL ─────────────────────────────────────────────────────────────────────
+
+def local_read(file_path, sheet_name, range_str):
+ ext = os.path.splitext(file_path)[1].lower()
+ parsed = parse_range(range_str)
+ r1, c1, r2, c2 = parsed if parsed else (1, 1, 1000, 26)
+
+ if ext == ".csv":
+ rows = []
+ with open(file_path, "r", encoding="utf-8") as f:
+ for line_no, line in enumerate(f, start=1):
+ if line_no < r1:
+ continue
+ if line_no > r2:
+ break
+ cells = line.rstrip("\n").split(",")
+ rows.append(cells[c1 - 1 : c2])
+ return {"source": "local", "operation": "read", "path": file_path,
+ "rows": len(rows), "data": rows}
+ else:
+ import openpyxl
+ wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
+ ws = wb[sheet_name] if sheet_name in wb.sheetnames else wb.active
+ rows = []
+ for r_idx, row in enumerate(ws.iter_rows(min_row=r1, max_row=r2,
+ min_col=c1, max_col=c2,
+ values_only=True), start=r1):
+ if any(v is not None for v in row):
+ rows.append([v if v is not None else None for v in row])
+ wb.close()
+ return {"source": "local", "operation": "read", "path": file_path,
+ "rows": len(rows), "data": rows}
+
+
+def local_write(file_path, sheet_name, range_str, data, append=False):
+ import openpyxl
+ parsed = parse_range(range_str)
+ r1, c1 = (parsed[0], parsed[1]) if parsed else (1, 1)
+
+ if append and os.path.exists(file_path):
+ wb = openpyxl.load_workbook(file_path)
+ else:
+ wb = openpyxl.Workbook()
+
+ if sheet_name in wb.sheetnames:
+ ws = wb[sheet_name]
+ else:
+ ws = wb.create_sheet(sheet_name)
+ # Remove default empty sheet if it exists
+ if "Sheet" in wb.sheetnames and ws.title != "Sheet":
+ del wb["Sheet"]
+
+ start_row = r1
+ if append:
+ start_row = ws.max_row + 1 if ws.max_row else 1
+
+ rows_written = 0
+ for ri, row in enumerate(data):
+ for ci, val in enumerate(row):
+ ws.cell(row=start_row + ri, column=c1 + ci, value=val)
+ rows_written += 1
+
+ wb.save(file_path)
+ return {"source": "local", "operation": "append" if append else "write",
+ "path": file_path, "rows_written": rows_written}
+
+
+def local_clear(file_path, sheet_name, range_str):
+ import openpyxl
+ parsed = parse_range(range_str)
+ r1, c1, r2, c2 = parsed if parsed else (1, 1, 1000, 26)
+
+ wb = openpyxl.load_workbook(file_path)
+ ws = wb[sheet_name] if sheet_name in wb.sheetnames else wb.active
+ for r in range(r1, r2 + 1):
+ for c in range(c1, c2 + 1):
+ ws.cell(row=r, column=c).value = None
+ wb.save(file_path)
+ return {"source": "local", "operation": "clear", "path": file_path}
+
+
+# ── GOOGLE SHEETS ─────────────────────────────────────────────────────────────
+
+def _get_gspread_client(credentials_path):
+ import gspread
+ if credentials_path:
+ return gspread.service_account(filename=credentials_path)
+ else:
+ # Anonymous / public read-only via API key not supported by gspread.
+ # Fall back to requests for public sheets.
+ return None
+
+
+def google_read(spreadsheet_id, sheet_name, range_str, credentials_path):
+ import gspread
+ if credentials_path:
+ gc = gspread.service_account(filename=credentials_path)
+ sh = gc.open_by_key(spreadsheet_id)
+ ws = sh.worksheet(sheet_name)
+ full_range = f"{sheet_name}!{range_str}"
+ rows = ws.get(range_str)
+ else:
+ # Public sheet — use requests directly (no auth needed)
+ import requests
+ url = (f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}"
+ f"/values/{sheet_name}!{range_str}")
+ resp = requests.get(url)
+ if not resp.ok:
+ return {"error": f"HTTP {resp.status_code}: {resp.text[:200]}"}
+ rows = resp.json().get("values", [])
+
+ return {"source": "google", "operation": "read", "sheet_id": spreadsheet_id,
+ "range": range_str, "rows": len(rows), "data": rows}
+
+
+def google_write(spreadsheet_id, sheet_name, range_str, data, credentials_path, append=False):
+ import gspread
+ gc = gspread.service_account(filename=credentials_path)
+ sh = gc.open_by_key(spreadsheet_id)
+ ws = sh.worksheet(sheet_name)
+ if append:
+ result = ws.append_rows(data, value_input_option="USER_ENTERED",
+ insert_data_option="INSERT_ROWS")
+ updated = result.get("updates", {}).get("updatedCells", len(data))
+ else:
+ result = ws.update(range_str, data, value_input_option="USER_ENTERED")
+ updated = result.get("updatedCells", len(data))
+ return {"source": "google", "operation": "append" if append else "write",
+ "sheet_id": spreadsheet_id, "updated_cells": updated}
+
+
+def google_clear(spreadsheet_id, sheet_name, range_str, credentials_path):
+ import gspread
+ gc = gspread.service_account(filename=credentials_path)
+ sh = gc.open_by_key(spreadsheet_id)
+ ws = sh.worksheet(sheet_name)
+ ws.batch_clear([range_str])
+ return {"source": "google", "operation": "clear", "sheet_id": spreadsheet_id}
+
+
+# ── MAIN ──────────────────────────────────────────────────────────────────────
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--args", required=True)
+ parsed = parser.parse_args()
+
+ try:
+ args = json.loads(parsed.args)
+ except json.JSONDecodeError as e:
+ print(json.dumps({"error": f"Invalid --args JSON: {e}"}))
+ sys.exit(1)
+
+ source = args.get("source", "local")
+ operation = args.get("operation", "read")
+ file_path = args.get("file_path", "")
+ spreadsheet_id = args.get("spreadsheet_id", "")
+ sheet_name = args.get("sheet_name", "Sheet1")
+ range_str = args.get("range", "A1:Z1000")
+ credentials_path = args.get("credentials_path", "")
+ data = args.get("data", [])
+
+ # Normalise data: may be a list of rows or a wrapped object
+ if isinstance(data, dict) and "data" in data:
+ data = data["data"]
+ if not isinstance(data, list):
+ data = []
+
+ try:
+ if source == "local":
+ if not file_path:
+ result = {"error": "file_path is required for source=local"}
+ elif operation == "read":
+ result = local_read(file_path, sheet_name, range_str)
+ elif operation in ("write", "append"):
+ result = local_write(file_path, sheet_name, range_str, data,
+ append=(operation == "append"))
+ elif operation == "clear":
+ result = local_clear(file_path, sheet_name, range_str)
+ else:
+ result = {"error": f"Unknown operation: {operation}"}
+
+ elif source == "google":
+ if not spreadsheet_id:
+ result = {"error": "spreadsheet_id is required for source=google"}
+ elif operation == "read":
+ result = google_read(spreadsheet_id, sheet_name, range_str, credentials_path)
+ elif operation in ("write", "append"):
+ if not credentials_path:
+ result = {"error": "credentials_path is required for write/append to Google Sheets"}
+ else:
+ result = google_write(spreadsheet_id, sheet_name, range_str, data,
+ credentials_path, append=(operation == "append"))
+ elif operation == "clear":
+ if not credentials_path:
+ result = {"error": "credentials_path is required for clear on Google Sheets"}
+ else:
+ result = google_clear(spreadsheet_id, sheet_name, range_str, credentials_path)
+ else:
+ result = {"error": f"Unknown operation: {operation}"}
+ else:
+ result = {"error": f"Unknown source: {source}"}
+
+ except Exception as e:
+ result = {"error": str(e)}
+
+ print(json.dumps(result))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/fincept-qt/scripts/yfinance_data.py b/fincept-qt/scripts/yfinance_data.py
index 7177eb363..1adad76f5 100644
--- a/fincept-qt/scripts/yfinance_data.py
+++ b/fincept-qt/scripts/yfinance_data.py
@@ -278,10 +278,14 @@ def get_batch_quotes(symbols):
continue
hist = hist.dropna(how='all')
- current_price = float(hist['Close'].iloc[-1])
+ raw_price = hist['Close'].iloc[-1]
+ if pd.isna(raw_price):
+ continue
+ current_price = float(raw_price)
# Use previous trading day close for accurate daily change.
# With period="5d" we always have >= 2 rows for normally-traded instruments.
- previous_close = float(hist['Close'].iloc[-2]) if len(hist) >= 2 else current_price
+ raw_prev = hist['Close'].iloc[-2] if len(hist) >= 2 else raw_price
+ previous_close = float(raw_prev) if not pd.isna(raw_prev) else current_price
change = current_price - previous_close
change_percent = (change / previous_close) * 100 if previous_close else 0
diff --git a/fincept-qt/src/screens/node_editor/canvas/EdgeItem.cpp b/fincept-qt/src/screens/node_editor/canvas/EdgeItem.cpp
index 306035fef..72e6ce361 100644
--- a/fincept-qt/src/screens/node_editor/canvas/EdgeItem.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/EdgeItem.cpp
@@ -2,6 +2,10 @@
#include "screens/node_editor/canvas/PortItem.h"
+#include <QAction>
+#include <QGraphicsSceneContextMenuEvent>
+#include <QKeyEvent>
+#include <QMenu>
#include <QPainter>
#include <QPainterPath>
#include <QTimerEvent>
@@ -11,6 +15,8 @@ namespace fincept::workflow {
EdgeItem::EdgeItem(const QString& id, PortItem* source, PortItem* target, QGraphicsItem* parent)
: QGraphicsPathItem(parent), id_(id), source_(source), target_(target) {
setFlag(ItemIsSelectable);
+ setFlag(ItemIsFocusable);
+ setAcceptHoverEvents(true);
setZValue(0); // edges behind nodes
setPen(QPen(QColor("#4a4a4a"), 2.0, Qt::SolidLine, Qt::RoundCap));
@@ -33,12 +39,17 @@ void EdgeItem::adjust() {
prepareGeometryChange();
+ // source_ is always the Output port, target_ is always the Input port.
+ // Output ports sit on the right side of their node, input ports on the left.
+ // Always curve rightward from the output: control point 1 bows right from p1,
+ // control point 2 bows left from p2 — giving a natural left-to-right S-less flow
+ // regardless of node positions on the canvas.
QPointF p1 = source_->scene_center();
QPointF p2 = target_->scene_center();
qreal dx = std::abs(p2.x() - p1.x()) * 0.5;
- if (dx < 40.0)
- dx = 40.0;
+ if (dx < 60.0)
+ dx = 60.0;
QPainterPath path;
path.moveTo(p1);
@@ -78,20 +89,44 @@ void EdgeItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget
else
color = QColor("#4a4a4a");
- QPen pen(color, 2.0, animated_ ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap);
- if (animated_)
+ QPen pen(color, 2.0, Qt::SolidLine, Qt::RoundCap);
+ if (animated_) {
+ pen.setStyle(Qt::CustomDashLine);
+ pen.setDashPattern({6.0, 4.0}); // 6px dash, 4px gap
pen.setDashOffset(dash_offset_);
+ }
painter->setPen(pen);
painter->drawPath(path());
}
void EdgeItem::timerEvent(QTimerEvent* event) {
if (event->timerId() == anim_timer_id_) {
- dash_offset_ += 1.0;
+ dash_offset_ -= 1.0; // negative offset advances dashes along path direction (left → right)
update();
}
}
+void EdgeItem::keyPressEvent(QKeyEvent* event) {
+ if (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace) {
+ emit delete_requested(id_);
+ event->accept();
+ } else {
+ QGraphicsPathItem::keyPressEvent(event);
+ }
+}
+
+void EdgeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) {
+ QMenu menu;
+ menu.setStyleSheet("QMenu { background: #1e1e1e; color: #e5e5e5; border: 1px solid #2a2a2a;"
+ " font-family: Consolas; font-size: 12px; }"
+ "QMenu::item { padding: 4px 20px; }"
+ "QMenu::item:selected { background: #dc2626; color: #ffffff; }");
+ auto* del = menu.addAction("Delete Connection");
+ if (menu.exec(event->screenPos()) == del)
+ emit delete_requested(id_);
+ event->accept();
+}
+
QVariant EdgeItem::itemChange(GraphicsItemChange change, const QVariant& value) {
if (change == ItemSelectedHasChanged && value.toBool())
emit edge_selected(id_);
diff --git a/fincept-qt/src/screens/node_editor/canvas/EdgeItem.h b/fincept-qt/src/screens/node_editor/canvas/EdgeItem.h
index ba2785e6b..306659fc6 100644
--- a/fincept-qt/src/screens/node_editor/canvas/EdgeItem.h
+++ b/fincept-qt/src/screens/node_editor/canvas/EdgeItem.h
@@ -1,6 +1,8 @@
#pragma once
#include <QGraphicsPathItem>
+#include <QGraphicsSceneContextMenuEvent>
+#include <QKeyEvent>
#include <QObject>
namespace fincept::workflow {
@@ -29,10 +31,13 @@ class EdgeItem : public QObject, public QGraphicsPathItem {
signals:
void edge_selected(const QString& id);
+ void delete_requested(const QString& id);
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant& value) override;
void timerEvent(QTimerEvent* event) override;
+ void keyPressEvent(QKeyEvent* event) override;
+ void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override;
private:
QString id_;
diff --git a/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp b/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
index 2c502364d..6fbf16ffe 100644
--- a/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/NodeScene.cpp
@@ -59,6 +59,7 @@ EdgeItem* NodeScene::add_edge(const EdgeDef& def) {
edges_.insert(def.id, edge);
connect(edge, &EdgeItem::edge_selected, this, [this](const QString& id) { Q_UNUSED(id); });
+ connect(edge, &EdgeItem::delete_requested, this, &NodeScene::remove_edge);
emit edge_added(def.id);
return edge;
diff --git a/fincept-qt/src/screens/node_editor/canvas/TempEdge.cpp b/fincept-qt/src/screens/node_editor/canvas/TempEdge.cpp
index b0efdb044..6777088b1 100644
--- a/fincept-qt/src/screens/node_editor/canvas/TempEdge.cpp
+++ b/fincept-qt/src/screens/node_editor/canvas/TempEdge.cpp
@@ -19,10 +19,12 @@ void TempEdge::update_target(const QPointF& scene_pos) {
QPointF p2 = scene_pos;
qreal dx = std::abs(p2.x() - p1.x()) * 0.5;
- if (dx < 40.0)
- dx = 40.0;
+ if (dx < 60.0)
+ dx = 60.0;
- // Reverse control points if dragging from input port
+ // Always bow toward the target: output ports exit rightward, input ports enter leftward.
+ // When dragging from an output port: cp1 goes right, cp2 approaches from the left.
+ // When dragging from an input port (connecting backwards): mirror so the curve still looks natural.
bool from_output = (source_->def().direction == PortDirection::Output);
qreal cx1 = from_output ? p1.x() + dx : p1.x() - dx;
qreal cx2 = from_output ? p2.x() - dx : p2.x() + dx;
diff --git a/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.cpp b/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.cpp
index 811a9a09d..af2e1536a 100644
--- a/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.cpp
+++ b/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.cpp
@@ -1,17 +1,176 @@
#include "screens/node_editor/properties/ExecutionResultsPanel.h"
#include <QFrame>
+#include <QHBoxLayout>
+#include <QJsonArray>
#include <QJsonDocument>
#include <QLabel>
+#include <QPushButton>
#include <QScrollArea>
+#include <QScrollBar>
+#include <QClipboard>
+#include <QGuiApplication>
+#include <QTimer>
namespace fincept::workflow {
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+static QString format_duration(int ms) {
+ if (ms < 1000) return QString("%1ms").arg(ms);
+ return QString("%1s").arg(ms / 1000.0, 0, 'f', 1);
+}
+
+static QString value_to_string(const QJsonValue& v) {
+ if (v.isString()) return v.toString();
+ if (v.isDouble()) return QString::number(v.toDouble(), 'g', 6);
+ if (v.isBool()) return v.toBool() ? "true" : "false";
+ if (v.isNull() || v.isUndefined()) return "—";
+ if (v.isArray())
+ return QString::fromUtf8(QJsonDocument(v.toArray()).toJson(QJsonDocument::Compact));
+ if (v.isObject())
+ return QString::fromUtf8(QJsonDocument(v.toObject()).toJson(QJsonDocument::Compact));
+ return {};
+}
+
+// Build a result card widget for a single node execution
+static QWidget* make_result_card(const NodeExecutionResult& result) {
+ bool ok = result.success;
+
+ auto* card = new QWidget;
+ card->setObjectName("resultCard");
+ card->setStyleSheet(
+ QString("QWidget#resultCard {"
+ " background: #161616;"
+ " border-left: 3px solid %1;"
+ " border-bottom: 1px solid #222;"
+ " margin: 0;"
+ "}").arg(ok ? "#16a34a" : "#dc2626"));
+
+ auto* vl = new QVBoxLayout(card);
+ vl->setContentsMargins(10, 6, 10, 6);
+ vl->setSpacing(4);
+
+ // ── Header row ─────────────────────────────────────────────────
+ auto* header_row = new QWidget;
+ auto* hl = new QHBoxLayout(header_row);
+ hl->setContentsMargins(0, 0, 0, 0);
+ hl->setSpacing(8);
+
+ // Status badge
+ auto* badge = new QLabel(ok ? "✓" : "✗");
+ badge->setFixedWidth(16);
+ badge->setAlignment(Qt::AlignCenter);
+ badge->setStyleSheet(QString("color: %1; font-family: Consolas; font-size: 11px;"
+ " font-weight: bold;").arg(ok ? "#16a34a" : "#dc2626"));
+ hl->addWidget(badge);
+
+ // Node ID (truncated)
+ auto* id_lbl = new QLabel(result.node_id.left(8) + "…");
+ id_lbl->setStyleSheet("color: #525252; font-family: Consolas; font-size: 9px;");
+ id_lbl->setToolTip(result.node_id);
+ hl->addWidget(id_lbl);
+
+ hl->addStretch();
+
+ // Duration
+ auto* dur_lbl = new QLabel(format_duration(result.duration_ms));
+ dur_lbl->setStyleSheet("color: #525252; font-family: Consolas; font-size: 9px;");
+ hl->addWidget(dur_lbl);
+
+ vl->addWidget(header_row);
+
+ // ── Content ────────────────────────────────────────────────────
+ if (!ok) {
+ // Error message
+ auto* err = new QLabel(result.error.isEmpty() ? "Unknown error" : result.error);
+ err->setWordWrap(true);
+ err->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ err->setStyleSheet("color: #f87171; font-family: Consolas; font-size: 10px;"
+ " background: transparent; padding: 2px 0;");
+ vl->addWidget(err);
+ } else if (result.output.isObject()) {
+ auto obj = result.output.toObject();
+
+ // LLM / Agent response
+ if (obj.contains("response")) {
+ QString response = obj.value("response").toString();
+
+ // Replace literal \n sequences with actual newlines
+ response.replace("\\n", "\n");
+
+ auto* text = new QLabel(response);
+ text->setWordWrap(true);
+ text->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ text->setStyleSheet("color: #e5e5e5; font-family: Consolas; font-size: 10px;"
+ " background: transparent; line-height: 1.4;");
+ vl->addWidget(text);
+
+ // Show exec time if present
+ if (obj.contains("exec_ms")) {
+ auto* meta = new QLabel(QString("Agent ran in %1ms")
+ .arg(obj.value("exec_ms").toInt()));
+ meta->setStyleSheet("color: #525252; font-family: Consolas; font-size: 9px;");
+ vl->addWidget(meta);
+ }
+ }
+ // Price / market data
+ else if (obj.contains("price") && obj.contains("symbol")) {
+ double price = obj["price"].toDouble();
+ auto* price_lbl = new QLabel(
+ QString("%1 $%2").arg(obj["symbol"].toString()).arg(price, 0, 'f', 2));
+ price_lbl->setStyleSheet("color: #e5e5e5; font-family: Consolas; font-size: 11px;"
+ " font-weight: bold;");
+ vl->addWidget(price_lbl);
+ }
+ // Generic key-value pairs
+ else {
+ auto* grid = new QWidget;
+ auto* gl = new QVBoxLayout(grid);
+ gl->setContentsMargins(0, 0, 0, 0);
+ gl->setSpacing(2);
+
+ for (auto it = obj.constBegin(); it != obj.constEnd(); ++it) {
+ auto* row = new QWidget;
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(8);
+
+ auto* key = new QLabel(it.key() + ":");
+ key->setFixedWidth(110);
+ key->setStyleSheet("color: #808080; font-family: Consolas; font-size: 10px;");
+ rl->addWidget(key);
+
+ QString valStr = value_to_string(it.value());
+ auto* val = new QLabel(valStr);
+ val->setWordWrap(true);
+ val->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ val->setStyleSheet("color: #e5e5e5; font-family: Consolas; font-size: 10px;");
+ rl->addWidget(val, 1);
+
+ gl->addWidget(row);
+ }
+ vl->addWidget(grid);
+ }
+ } else if (!result.output.isNull() && !result.output.isUndefined()) {
+ // Scalar output
+ auto* val = new QLabel(value_to_string(result.output));
+ val->setWordWrap(true);
+ val->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ val->setStyleSheet("color: #e5e5e5; font-family: Consolas; font-size: 10px;");
+ vl->addWidget(val);
+ }
+
+ return card;
+}
+
+// ── ExecutionResultsPanel ──────────────────────────────────────────────────
+
ExecutionResultsPanel::ExecutionResultsPanel(QWidget* parent) : QWidget(parent) {
- setFixedHeight(180);
+ setFixedHeight(34); // header-only until execution starts (collapsed by default)
setObjectName("executionResultsPanel");
build_ui();
- hide(); // hidden by default, shown during execution
+ hide();
}
void ExecutionResultsPanel::build_ui() {
@@ -19,49 +178,116 @@ void ExecutionResultsPanel::build_ui() {
root->setContentsMargins(0, 0, 0, 0);
root->setSpacing(0);
- // ── Separator ──────────────────────────────────────────────────
+ // ── Top separator ──────────────────────────────────────────────
auto* sep = new QFrame;
sep->setFixedHeight(1);
sep->setStyleSheet("background: #2a2a2a; border: none;");
root->addWidget(sep);
- // ── Header ─────────────────────────────────────────────────────
+ // ── Header bar ────────────────────────────────────────────────
auto* header = new QWidget;
- header->setFixedHeight(28);
- header->setStyleSheet("background: #1e1e1e;");
+ header->setFixedHeight(32);
+ header->setStyleSheet("background: #1a1a1a;");
auto* hl = new QHBoxLayout(header);
- hl->setContentsMargins(10, 0, 10, 0);
+ hl->setContentsMargins(10, 0, 8, 0);
+ hl->setSpacing(8);
+
+ // Collapse toggle
+ collapse_btn_ = new QPushButton("▸");
+ collapse_btn_->setFixedSize(18, 18);
+ collapse_btn_->setStyleSheet("QPushButton { background: transparent; color: #808080;"
+ " border: none; font-size: 10px; }"
+ "QPushButton:hover { color: #e5e5e5; }");
+ collapse_btn_->setToolTip("Expand / Collapse");
+ connect(collapse_btn_, &QPushButton::clicked, this,
+ [this]() { set_collapsed(!collapsed_); });
+ hl->addWidget(collapse_btn_);
auto* title = new QLabel("EXECUTION RESULTS");
- title->setStyleSheet("color: #d97706; font-family: Consolas; font-size: 11px;"
- "font-weight: bold; letter-spacing: 0.5px;");
+ title->setStyleSheet("color: #d97706; font-family: Consolas; font-size: 10px;"
+ " font-weight: bold; letter-spacing: 0.5px;");
hl->addWidget(title);
+ // Node counter badge
+ node_counter_ = new QLabel("");
+ node_counter_->setStyleSheet("color: #525252; font-family: Consolas; font-size: 10px;");
+ hl->addWidget(node_counter_);
+
hl->addStretch();
+ // Status label
status_label_ = new QLabel("IDLE");
- status_label_->setStyleSheet("color: #525252; font-family: Consolas; font-size: 10px; font-weight: bold;");
+ status_label_->setStyleSheet("color: #525252; font-family: Consolas;"
+ " font-size: 10px; font-weight: bold;");
hl->addWidget(status_label_);
+ // Separator
+ auto* vsep = new QFrame;
+ vsep->setFixedSize(1, 16);
+ vsep->setStyleSheet("background: #2a2a2a; border: none;");
+ hl->addWidget(vsep);
+
+ // Clear button
+ clear_btn_ = new QPushButton("CLEAR");
+ clear_btn_->setFixedHeight(20);
+ clear_btn_->setStyleSheet("QPushButton { background: transparent; color: #525252;"
+ " border: none; font-family: Consolas; font-size: 10px; }"
+ "QPushButton:hover { color: #e5e5e5; }");
+ connect(clear_btn_, &QPushButton::clicked, this, &ExecutionResultsPanel::clear);
+ hl->addWidget(clear_btn_);
+
+ // Copy button
+ copy_btn_ = new QPushButton("COPY");
+ copy_btn_->setFixedHeight(20);
+ copy_btn_->setStyleSheet("QPushButton { background: transparent; color: #525252;"
+ " border: none; font-family: Consolas; font-size: 10px; }"
+ "QPushButton:hover { color: #d97706; }");
+ copy_btn_->setToolTip("Copy all results to clipboard");
+ connect(copy_btn_, &QPushButton::clicked, this, [this]() {
+ QGuiApplication::clipboard()->setText(copy_buffer_);
+ copy_btn_->setText("COPIED!");
+ copy_btn_->setStyleSheet("QPushButton { background: transparent; color: #16a34a;"
+ " border: none; font-family: Consolas; font-size: 10px; }");
+ QTimer::singleShot(1500, copy_btn_, [this]() {
+ copy_btn_->setText("COPY");
+ copy_btn_->setStyleSheet(
+ "QPushButton { background: transparent; color: #525252;"
+ " border: none; font-family: Consolas; font-size: 10px; }"
+ "QPushButton:hover { color: #d97706; }");
+ });
+ });
+ hl->addWidget(copy_btn_);
+
root->addWidget(header);
- // ── Scrollable results ─────────────────────────────────────────
- auto* scroll = new QScrollArea;
- scroll->setWidgetResizable(true);
- scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- scroll->setStyleSheet("QScrollArea { background: #141414; border: none; }"
- "QScrollBar:vertical { background: #141414; width: 6px; }"
- "QScrollBar::handle:vertical { background: #4a4a4a; min-height: 20px; }"
- "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
+ // ── Scrollable results area ────────────────────────────────────
+ scroll_area_ = new QScrollArea;
+ scroll_area_->setWidgetResizable(true);
+ scroll_area_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ scroll_area_->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
+ scroll_area_->setStyleSheet(
+ "QScrollArea { background: #111; border: none; }"
+ "QScrollBar:vertical { background: #111; width: 5px; border: none; }"
+ "QScrollBar::handle:vertical { background: #333; min-height: 20px; border-radius: 2px; }"
+ "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }");
results_container_ = new QWidget;
+ results_container_->setStyleSheet("background: #111;");
results_layout_ = new QVBoxLayout(results_container_);
- results_layout_->setContentsMargins(8, 4, 8, 4);
- results_layout_->setSpacing(2);
+ results_layout_->setContentsMargins(0, 0, 0, 0);
+ results_layout_->setSpacing(0);
results_layout_->addStretch();
- scroll->setWidget(results_container_);
- root->addWidget(scroll, 1);
+ scroll_area_->setWidget(results_container_);
+ scroll_area_->hide(); // starts collapsed
+ root->addWidget(scroll_area_, 1);
+}
+
+void ExecutionResultsPanel::set_collapsed(bool collapsed) {
+ collapsed_ = collapsed;
+ collapse_btn_->setText(collapsed_ ? "▸" : "▾");
+ scroll_area_->setVisible(!collapsed_);
+ setFixedHeight(collapsed_ ? 34 : 280);
}
void ExecutionResultsPanel::clear() {
@@ -71,73 +297,84 @@ void ExecutionResultsPanel::clear() {
item->widget()->deleteLater();
delete item;
}
+ node_count_ = 0;
+ error_count_ = 0;
+ copy_buffer_.clear();
+ node_counter_->setText("");
status_label_->setText("IDLE");
- status_label_->setStyleSheet("color: #525252; font-family: Consolas; font-size: 10px; font-weight: bold;");
+ status_label_->setStyleSheet("color: #525252; font-family: Consolas;"
+ " font-size: 10px; font-weight: bold;");
}
void ExecutionResultsPanel::set_started(const QString& workflow_id) {
+ Q_UNUSED(workflow_id);
clear();
show();
- Q_UNUSED(workflow_id);
- status_label_->setText("RUNNING...");
- status_label_->setStyleSheet("color: #d97706; font-family: Consolas; font-size: 10px; font-weight: bold;");
+ set_collapsed(false); // auto-expand when execution starts
+ status_label_->setText("RUNNING…");
+ status_label_->setStyleSheet("color: #d97706; font-family: Consolas;"
+ " font-size: 10px; font-weight: bold;");
}
void ExecutionResultsPanel::add_node_result(const NodeExecutionResult& result) {
- auto* row = new QWidget;
- row->setFixedHeight(22);
- auto* rl = new QHBoxLayout(row);
- rl->setContentsMargins(4, 0, 4, 0);
- rl->setSpacing(8);
-
- // Status dot
- QString dot_color = result.success ? "#16a34a" : "#dc2626";
- auto* dot = new QLabel(result.success ? "OK" : "ERR");
- dot->setFixedWidth(28);
- dot->setAlignment(Qt::AlignCenter);
- dot->setStyleSheet(QString("color: %1; font-family: Consolas; font-size: 9px; font-weight: bold;").arg(dot_color));
- rl->addWidget(dot);
+ ++node_count_;
+ if (!result.success) ++error_count_;
- // Node ID (truncated)
- auto* id_label = new QLabel(result.node_id.left(12));
- id_label->setFixedWidth(90);
- id_label->setStyleSheet("color: #808080; font-family: Consolas; font-size: 10px;");
- rl->addWidget(id_label);
-
- // Duration
- auto* dur = new QLabel(QString("%1ms").arg(result.duration_ms));
- dur->setFixedWidth(50);
- dur->setStyleSheet("color: #525252; font-family: Consolas; font-size: 10px;");
- rl->addWidget(dur);
+ // Update counter
+ QString counter = QString("%1 node%2").arg(node_count_).arg(node_count_ == 1 ? "" : "s");
+ if (error_count_ > 0)
+ counter += QString(" %1 error%2").arg(error_count_).arg(error_count_ == 1 ? "" : "s");
+ node_counter_->setText(counter);
+ node_counter_->setStyleSheet(error_count_ > 0
+ ? "color: #dc2626; font-family: Consolas; font-size: 10px;"
+ : "color: #525252; font-family: Consolas; font-size: 10px;");
- // Output preview or error
- QString preview;
+ // Append plain-text representation to copy buffer
+ copy_buffer_ += QString("[%1] %2 %3\n")
+ .arg(result.success ? "OK" : "ERR")
+ .arg(result.node_id.left(8))
+ .arg(format_duration(result.duration_ms));
if (!result.success) {
- preview = result.error;
+ copy_buffer_ += result.error + "\n";
} else if (result.output.isObject()) {
- preview = QString::fromUtf8(QJsonDocument(result.output.toObject()).toJson(QJsonDocument::Compact));
- } else if (result.output.isString()) {
- preview = result.output.toString();
+ auto obj = result.output.toObject();
+ if (obj.contains("response")) {
+ QString r = obj.value("response").toString();
+ r.replace("\\n", "\n");
+ copy_buffer_ += r + "\n";
+ } else {
+ copy_buffer_ += QString::fromUtf8(
+ QJsonDocument(obj).toJson(QJsonDocument::Indented)) + "\n";
+ }
} else {
- preview = "OK";
+ copy_buffer_ += value_to_string(result.output) + "\n";
}
- auto* output_label = new QLabel(preview);
- output_label->setStyleSheet(
- QString("color: %1; font-family: Consolas; font-size: 10px;").arg(result.success ? "#e5e5e5" : "#dc2626"));
- output_label->setTextInteractionFlags(Qt::TextSelectableByMouse);
- rl->addWidget(output_label, 1);
-
- int pos = results_layout_->count() - 1; // before stretch
- results_layout_->insertWidget(pos, row);
+ copy_buffer_ += "\n";
+
+ auto* card = make_result_card(result);
+ int pos = results_layout_->count() - 1; // before trailing stretch
+ results_layout_->insertWidget(pos, card);
+
+ // Auto-scroll to bottom
+ QTimer::singleShot(0, scroll_area_, [this]() {
+ scroll_area_->verticalScrollBar()->setValue(
+ scroll_area_->verticalScrollBar()->maximum());
+ });
}
void ExecutionResultsPanel::set_finished(const WorkflowExecutionResult& result) {
if (result.success) {
- status_label_->setText(QString("COMPLETED %1ms").arg(result.total_duration_ms));
- status_label_->setStyleSheet("color: #16a34a; font-family: Consolas; font-size: 10px; font-weight: bold;");
+ status_label_->setText(
+ QString("DONE %1").arg(format_duration(result.total_duration_ms)));
+ status_label_->setStyleSheet("color: #16a34a; font-family: Consolas;"
+ " font-size: 10px; font-weight: bold;");
} else {
- status_label_->setText(QString("FAILED %1").arg(result.error));
- status_label_->setStyleSheet("color: #dc2626; font-family: Consolas; font-size: 10px; font-weight: bold;");
+ QString msg = result.error.startsWith("Execution stopped")
+ ? "STOPPED"
+ : QString("FAILED %1").arg(result.error);
+ status_label_->setText(msg);
+ status_label_->setStyleSheet("color: #dc2626; font-family: Consolas;"
+ " font-size: 10px; font-weight: bold;");
}
}
diff --git a/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.h b/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.h
index 6bfdfd76b..4a17944a1 100644
--- a/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.h
+++ b/fincept-qt/src/screens/node_editor/properties/ExecutionResultsPanel.h
@@ -3,12 +3,14 @@
#include "screens/node_editor/NodeEditorTypes.h"
#include <QLabel>
+#include <QPushButton>
+#include <QScrollArea>
#include <QVBoxLayout>
#include <QWidget>
namespace fincept::workflow {
-/// Bottom drawer showing execution results per node.
+/// Bottom drawer showing per-node execution results with collapsible UI.
class ExecutionResultsPanel : public QWidget {
Q_OBJECT
public:
@@ -21,10 +23,20 @@ class ExecutionResultsPanel : public QWidget {
private:
void build_ui();
-
- QLabel* status_label_ = nullptr;
- QVBoxLayout* results_layout_ = nullptr;
- QWidget* results_container_ = nullptr;
+ void set_collapsed(bool collapsed);
+
+ QLabel* status_label_ = nullptr;
+ QLabel* node_counter_ = nullptr;
+ QPushButton* collapse_btn_ = nullptr;
+ QPushButton* clear_btn_ = nullptr;
+ QPushButton* copy_btn_ = nullptr;
+ QScrollArea* scroll_area_ = nullptr;
+ QWidget* results_container_ = nullptr;
+ QVBoxLayout* results_layout_ = nullptr;
+ bool collapsed_ = false;
+ int node_count_ = 0;
+ int error_count_ = 0;
+ QString copy_buffer_;
};
} // namespace fincept::workflow
diff --git a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp
index 14b40f739..ea1b2da31 100644
--- a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp
+++ b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.cpp
@@ -1,6 +1,16 @@
#include "screens/node_editor/properties/ParameterWidgets.h"
+#include "mcp/McpService.h"
+#include "services/agents/AgentService.h"
+#include "services/agents/AgentTypes.h"
+#include "services/file_manager/FileManagerService.h"
+#include "storage/repositories/LlmProfileRepository.h"
+
+#include <QFileDialog>
+#include <QFileInfo>
+#include <QHBoxLayout>
#include <QJsonDocument>
+#include <QPushButton>
namespace {
static const char* kInputStyle = "background: #1e1e1e; color: #e5e5e5; border: 1px solid #2a2a2a;"
@@ -114,6 +124,305 @@ QWidget* ParameterWidgetFactory::create(const ParamDef& param, const QJsonValue&
on_change(key, QJsonValue(text));
}
});
+ } else if (param.type == "file_managed") {
+ // Allowed extensions come from placeholder, e.g. "xlsx,csv" or "json"
+ QStringList allowed_exts;
+ if (!param.placeholder.isEmpty())
+ for (const QString& e : param.placeholder.split(','))
+ allowed_exts << e.trimmed().toLower();
+
+ // Build dropdown from FileManagerService — filter by allowed extensions
+ auto* row = new QWidget;
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(4);
+
+ auto* combo = new QComboBox;
+ combo->setStyleSheet(QString("QComboBox { %1 }"
+ "QComboBox::drop-down {"
+ " background: #2a2a2a; border: 1px solid #2a2a2a; width: 18px;"
+ "}"
+ "QComboBox QAbstractItemView {"
+ " background: #1e1e1e; color: #e5e5e5; border: 1px solid #2a2a2a;"
+ " selection-background-color: #d97706; font-family: Consolas;"
+ "}")
+ .arg(kInputStyle));
+
+ // Build file filter string for QFileDialog e.g. "Spreadsheets (*.xlsx *.csv)"
+ QString dialog_filter;
+ if (!allowed_exts.isEmpty()) {
+ QStringList stars;
+ for (const QString& e : allowed_exts) stars << "*." + e;
+ dialog_filter = allowed_exts.join("/").toUpper()
+ + " Files (" + stars.join(" ") + ");;All Files (*)";
+ } else {
+ dialog_filter = "All Files (*)";
+ }
+
+ // Populate combo from managed files; select_path forces selection after import
+ auto populate = [combo, allowed_exts](const QString& select_path = {}) {
+ QString prev = select_path.isEmpty()
+ ? combo->currentData().toString()
+ : select_path;
+ combo->clear();
+ combo->addItem("— select file —", QString());
+
+ auto& svc = fincept::services::FileManagerService::instance();
+ for (const auto& v : svc.all_files()) {
+ QJsonObject f = v.toObject();
+ QString stored_name = f.value("name").toString();
+ QString original_name = f.value("originalName").toString();
+ QString full_path = svc.full_path(stored_name);
+ QString ext = QFileInfo(original_name).suffix().toLower();
+
+ if (!allowed_exts.isEmpty() && !allowed_exts.contains(ext))
+ continue;
+
+ combo->addItem(original_name + " [" + ext.toUpper() + "]", full_path);
+
+ if (!prev.isEmpty() && full_path == prev)
+ combo->setCurrentIndex(combo->count() - 1);
+ }
+ };
+ populate();
+
+ rl->addWidget(combo, 1);
+
+ // Import button — opens file dialog, imports into FileManagerService, auto-selects
+ auto* import_btn = new QPushButton("+ Import");
+ import_btn->setFixedHeight(24);
+ import_btn->setToolTip("Import a file from your PC into the File Manager");
+ import_btn->setStyleSheet("QPushButton { background: #2a2a2a; color: #d97706;"
+ " border: 1px solid #3a3a3a; font-family: Consolas;"
+ " font-size: 10px; padding: 0 6px; }"
+ "QPushButton:hover { background: #3a3a3a; }");
+ rl->addWidget(import_btn);
+
+ layout->addWidget(row);
+
+ // Hint showing allowed extensions
+ if (!allowed_exts.isEmpty()) {
+ auto* hint = new QLabel("Accepted: " + allowed_exts.join(", ").toUpper()
+ + " • Or pick an already-imported file above");
+ hint->setStyleSheet("color: #525252; font-family: Consolas; font-size: 10px;");
+ hint->setWordWrap(true);
+ layout->addWidget(hint);
+ }
+
+ QObject::connect(combo, &QComboBox::currentIndexChanged, container,
+ [key, on_change, combo](int) {
+ on_change(key, QJsonValue(combo->currentData().toString()));
+ });
+
+ QObject::connect(import_btn, &QPushButton::clicked, container,
+ [populate, dialog_filter, key, on_change, combo, import_btn]() {
+ QString path = QFileDialog::getOpenFileName(
+ import_btn->window(),
+ "Import File",
+ QString(),
+ dialog_filter);
+ if (path.isEmpty()) return;
+
+ QString file_id = fincept::services::FileManagerService::instance()
+ .import_file(path, "workflow_node");
+ if (file_id.isEmpty()) return;
+
+ // Find the full managed path for the newly imported file
+ auto f = fincept::services::FileManagerService::instance()
+ .find_by_id(file_id);
+ QString full_path = fincept::services::FileManagerService::instance()
+ .full_path(f.name);
+
+ populate(full_path);
+ on_change(key, QJsonValue(full_path));
+ });
+ } else if (param.type == "agent_select") {
+ auto* row = new QWidget;
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(4);
+
+ auto* combo = new QComboBox;
+ combo->setStyleSheet(QString("QComboBox { %1 }"
+ "QComboBox::drop-down { background:#2a2a2a; border:1px solid #2a2a2a; width:18px; }"
+ "QComboBox QAbstractItemView { background:#1e1e1e; color:#e5e5e5;"
+ " border:1px solid #2a2a2a; selection-background-color:#7c3aed;"
+ " font-family:Consolas; }").arg(kInputStyle));
+
+ // Constrain combo so it never overflows the panel
+ combo->setMaximumWidth(260);
+ combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+
+ auto populate_agents = [combo, current_value]() {
+ QString saved = current_value.toString();
+ if (combo->count() > 0) saved = combo->currentData().toString();
+ combo->clear();
+ combo->addItem("— select agent —", QString());
+
+ const auto agents = fincept::services::AgentService::instance().cached_agents();
+ for (const auto& a : agents) {
+ QString label = a.name;
+ if (!a.category.isEmpty()) label += " [" + a.category + "]";
+ combo->addItem(label, a.id);
+ if (a.id == saved)
+ combo->setCurrentIndex(combo->count() - 1);
+ }
+ };
+
+ // Helper: wire one-shot discovery → populate
+ auto trigger_discovery = [populate_agents, combo]() {
+ auto& svc = fincept::services::AgentService::instance();
+ QObject::connect(&svc, &fincept::services::AgentService::agents_discovered,
+ combo, [populate_agents, combo](const QVector<fincept::services::AgentInfo>&,
+ const QVector<fincept::services::AgentCategory>&) {
+ populate_agents();
+ QObject::disconnect(&fincept::services::AgentService::instance(),
+ &fincept::services::AgentService::agents_discovered,
+ combo, nullptr);
+ });
+ svc.discover_agents();
+ };
+
+ // Always auto-discover on widget creation — don't make user navigate elsewhere
+ auto& svc = fincept::services::AgentService::instance();
+ if (svc.cached_agent_count() > 0) {
+ populate_agents(); // cache hot — fill immediately
+ } else {
+ combo->addItem("Loading agents…", QString());
+ trigger_discovery();
+ }
+
+ rl->addWidget(combo, 1);
+
+ auto* refresh_btn = new QPushButton("↻");
+ refresh_btn->setFixedSize(24, 24);
+ refresh_btn->setToolTip("Refresh agent list");
+ refresh_btn->setStyleSheet("QPushButton { background:#2a2a2a; color:#7c3aed;"
+ " border:1px solid #2a2a2a; font-size:13px; }"
+ "QPushButton:hover { background:#3a3a3a; }");
+ rl->addWidget(refresh_btn);
+ layout->addWidget(row);
+
+ QObject::connect(combo, &QComboBox::currentIndexChanged, container,
+ [key, on_change, combo](int) {
+ on_change(key, QJsonValue(combo->currentData().toString()));
+ });
+
+ QObject::connect(refresh_btn, &QPushButton::clicked, container,
+ [trigger_discovery]() { trigger_discovery(); });
+
+ } else if (param.type == "llm_select") {
+ // Dropdown populated from LlmProfileRepository
+ auto* combo = new QComboBox;
+ combo->setMaximumWidth(260);
+ combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ combo->setStyleSheet(QString("QComboBox { %1 }"
+ "QComboBox::drop-down { background:#2a2a2a; border:1px solid #2a2a2a; width:18px; }"
+ "QComboBox QAbstractItemView { background:#1e1e1e; color:#e5e5e5;"
+ " border:1px solid #2a2a2a; selection-background-color:#7c3aed;"
+ " font-family:Consolas; }").arg(kInputStyle));
+ combo->addItem("— agent default —", QString());
+
+ QString saved = current_value.toString();
+ auto res = fincept::LlmProfileRepository::instance().list_profiles();
+ if (res.is_ok()) {
+ for (const auto& p : res.value()) {
+ QString label = p.name + " [" + p.provider + " / " + p.model_id + "]";
+ combo->addItem(label, p.id);
+ if (p.id == saved)
+ combo->setCurrentIndex(combo->count() - 1);
+ }
+ }
+ layout->addWidget(combo);
+
+ auto* hint = new QLabel("Leave blank to use the LLM assigned to the agent in Agent Config");
+ hint->setStyleSheet("color:#525252; font-family:Consolas; font-size:10px;");
+ hint->setWordWrap(true);
+ layout->addWidget(hint);
+
+ QObject::connect(combo, &QComboBox::currentIndexChanged, container,
+ [key, on_change, combo](int) {
+ on_change(key, QJsonValue(combo->currentData().toString()));
+ });
+ } else if (param.type == "mcp_tool_select") {
+ // Dropdown + refresh, populated from McpService::get_all_tools()
+ // Displays: "Category / tool_name — description"
+ // Value stored: bare tool_name (internal) or "serverId__toolName" (external)
+ auto* row = new QWidget;
+ auto* rl = new QHBoxLayout(row);
+ rl->setContentsMargins(0, 0, 0, 0);
+ rl->setSpacing(4);
+
+ auto* combo = new QComboBox;
+ combo->setMaximumWidth(260);
+ combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ combo->setStyleSheet(QString("QComboBox { %1 }"
+ "QComboBox::drop-down { background:#2a2a2a; border:1px solid #2a2a2a; width:18px; }"
+ "QComboBox QAbstractItemView { background:#1e1e1e; color:#e5e5e5;"
+ " border:1px solid #2a2a2a; selection-background-color:#6366f1;"
+ " font-family:Consolas; }").arg(kInputStyle));
+
+ auto populate_tools = [combo, current_value]() {
+ QString saved = combo->count() > 0 ? combo->currentData().toString()
+ : current_value.toString();
+ combo->clear();
+ combo->addItem("— select tool —", QString());
+
+ auto tools = mcp::McpService::instance().get_all_tools();
+ // Group by category for readability — use server_name as group header hint
+ QString last_server;
+ for (const auto& t : tools) {
+ if (t.server_name != last_server) {
+ // Separator item (not selectable)
+ combo->addItem("── " + t.server_name + " ──", QString());
+ auto* model = qobject_cast<QStandardItemModel*>(combo->model());
+ if (model) {
+ auto* sep = model->item(combo->count() - 1);
+ sep->setFlags(sep->flags() & ~Qt::ItemIsEnabled);
+ sep->setData(QColor("#525252"), Qt::ForegroundRole);
+ }
+ last_server = t.server_name;
+ }
+ // Value: bare name for internal tools, "serverId__name" for external
+ QString value = t.is_internal ? t.name : (t.server_id + "__" + t.name);
+ QString label = t.name;
+ if (!t.description.isEmpty())
+ label += " — " + t.description.left(50);
+ combo->addItem(label, value);
+ if (value == saved)
+ combo->setCurrentIndex(combo->count() - 1);
+ }
+ };
+
+ combo->addItem("Loading tools…", QString());
+ // Populate async so we don't block the UI thread constructing the panel
+ QMetaObject::invokeMethod(combo, [populate_tools]() { populate_tools(); }, Qt::QueuedConnection);
+
+ rl->addWidget(combo, 1);
+
+ auto* refresh_btn = new QPushButton("↻");
+ refresh_btn->setFixedSize(24, 24);
+ refresh_btn->setToolTip("Refresh tool list");
+ refresh_btn->setStyleSheet("QPushButton { background:#2a2a2a; color:#6366f1;"
+ " border:1px solid #2a2a2a; font-size:13px; }"
+ "QPushButton:hover { background:#3a3a3a; }");
+ rl->addWidget(refresh_btn);
+ layout->addWidget(row);
+
+ auto* hint = new QLabel("All Fincept internal tools. Input JSON flows in as arguments.");
+ hint->setStyleSheet("color:#525252; font-family:Consolas; font-size:10px;");
+ hint->setWordWrap(true);
+ layout->addWidget(hint);
+
+ QObject::connect(combo, &QComboBox::currentIndexChanged, container,
+ [key, on_change, combo](int) {
+ QString val = combo->currentData().toString();
+ if (!val.isEmpty())
+ on_change(key, QJsonValue(val));
+ });
+
+ QObject::connect(refresh_btn, &QPushButton::clicked, container,
+ [populate_tools]() { populate_tools(); });
}
return container;
diff --git a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.h b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.h
index 345a9864d..f5eb3e6f6 100644
--- a/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.h
+++ b/fincept-qt/src/screens/node_editor/properties/ParameterWidgets.h
@@ -5,10 +5,12 @@
#include <QCheckBox>
#include <QComboBox>
#include <QDoubleSpinBox>
+#include <QHBoxLayout>
#include <QJsonValue>
#include <QLabel>
#include <QLineEdit>
#include <QPlainTextEdit>
+#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cpp
index 3e7e13854..acb66894f 100644
--- a/fincept-qt/src/services/agents/AgentService.cpp
+++ b/fincept-qt/src/services/agents/AgentService.cpp
@@ -42,6 +42,11 @@ void AgentService::clear_cache() {
LOG_INFO("AgentService", "Cache cleared");
}
+QVector<AgentInfo> AgentService::cached_agents() const {
+ QMutexLocker lock(&cache_mutex_);
+ return agents_cache_.data;
+}
+
int AgentService::cached_agent_count() const {
QMutexLocker lock(&cache_mutex_);
return agents_cache_.data.size();
diff --git a/fincept-qt/src/services/agents/AgentService.h b/fincept-qt/src/services/agents/AgentService.h
index 2c1ae2ea2..1542bbc2e 100644
--- a/fincept-qt/src/services/agents/AgentService.h
+++ b/fincept-qt/src/services/agents/AgentService.h
@@ -87,6 +87,7 @@ class AgentService : public QObject {
void clear_cache();
void clear_response_cache();
int cached_agent_count() const;
+ QVector<AgentInfo> cached_agents() const;
QJsonObject get_cache_stats() const;
signals:
diff --git a/fincept-qt/src/services/markets/MarketDataService.cpp b/fincept-qt/src/services/markets/MarketDataService.cpp
index 5bc7c225d..451d61a44 100644
--- a/fincept-qt/src/services/markets/MarketDataService.cpp
+++ b/fincept-qt/src/services/markets/MarketDataService.cpp
@@ -406,7 +406,7 @@ void MarketDataService::fetch_sparklines(const QStringList& symbols, SparklineCa
args << "batch_sparklines" << symbols;
python::PythonRunner::instance().run(
- "yfinance_data", args,
+ "yfinance_data.py", args,
[cb](python::PythonResult result) {
if (!result.success || result.output.trimmed().isEmpty()) {
LOG_WARN("MarketData", "Sparklines failed: " + result.error.left(200));
diff --git a/fincept-qt/src/services/workflow/WorkflowExecutor.cpp b/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
index 36855fcc6..dfe89c92c 100644
--- a/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
+++ b/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
@@ -141,8 +141,23 @@ void WorkflowExecutor::execute_from(const WorkflowDef& workflow, const QString&
}
void WorkflowExecutor::stop() {
+ if (!running_)
+ return;
stop_requested_ = true;
LOG_INFO("Executor", "Stop requested");
+ // Force immediate completion — don't wait for the in-flight node to finish.
+ // Set running_ false and emit execution_finished right now so the UI unlocks.
+ running_ = false;
+ WorkflowExecutionResult wr;
+ wr.workflow_id = workflow_.id;
+ wr.total_duration_ms = static_cast<int>(QDateTime::currentMSecsSinceEpoch() - start_time_ms_);
+ wr.success = false;
+ wr.error = "Execution stopped by user";
+ for (auto it = results_.constBegin(); it != results_.constEnd(); ++it)
+ wr.node_results.append(it.value());
+ ExecutionHooks::instance().emit_workflow_end(workflow_.id, false, wr.total_duration_ms);
+ AuditLogger::instance().log(AuditAction::WorkflowFailed, workflow_.id, {}, {}, "Stopped by user");
+ emit execution_finished(wr);
}
// ── Graph construction ─────────────────────────────────────────────────
diff --git a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
index 47a720808..e6e57f930 100644
--- a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
+++ b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
@@ -1,12 +1,16 @@
#include "services/workflow/adapters/ServiceBridges.h"
#include "core/logging/Logger.h"
+#include "mcp/McpService.h"
#include "services/workflow/AuditLogger.h"
#include "services/workflow/ConfirmationService.h"
#include "services/workflow/NodeRegistry.h"
#include "services/workflow/RiskManager.h"
+#include "trading/ExchangeService.h"
#include <QDateTime>
+#include <QPointer>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::workflow {
@@ -49,6 +53,42 @@ void wire_market_data_bridges(NodeRegistry& registry) {
};
}
+ // Crypto Price — uses ExchangeService (Kraken public API, no key needed)
+ auto* crypto_price_def = const_cast<NodeTypeDef*>(registry.find("market.get_crypto_price"));
+ if (crypto_price_def) {
+ crypto_price_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString base = params.value("symbol").toString("BTC").toUpper();
+ QString quote = params.value("quote").toString("USD").toUpper();
+ QString symbol = base + "/" + quote; // Kraken format: BTC/USD
+
+ (void)QtConcurrent::run([symbol, cb]() {
+ auto& svc = trading::ExchangeService::instance();
+ trading::TickerData t = svc.fetch_ticker(symbol);
+
+ if (t.last <= 0.0) {
+ cb(false, {}, QString("No price data for %1").arg(symbol));
+ return;
+ }
+
+ QJsonObject out;
+ out["symbol"] = symbol;
+ out["price"] = t.last;
+ out["bid"] = t.bid;
+ out["ask"] = t.ask;
+ out["high"] = t.high;
+ out["low"] = t.low;
+ out["change"] = t.change;
+ out["change_pct"] = t.percentage;
+ out["volume"] = t.base_volume;
+ out["exchange"] = "kraken";
+ out["timestamp"] = static_cast<qint64>(t.timestamp);
+ cb(true, out, {});
+ LOG_DEBUG("MarketBridge", QString("Crypto price fetched: %1 = %2").arg(symbol).arg(t.last));
+ });
+ };
+ }
+
// Wire remaining market data nodes with placeholder executors
for (const auto& id : {"market.get_depth", "market.get_stats", "market.get_fundamentals", "market.get_economics",
"market.get_news"}) {
@@ -323,7 +363,68 @@ static void wire_utility_bridges(NodeRegistry& registry) {
LOG_INFO("ServiceBridges", "Utility bridges wired");
}
+static void wire_mcp_bridges(NodeRegistry& registry) {
+ auto* def = const_cast<NodeTypeDef*>(registry.find("mcp.tool_call"));
+ if (!def) return;
+
+ def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString tool = params.value("tool").toString().trimmed();
+ if (tool.isEmpty()) {
+ cb(false, {}, "MCP Tool: 'tool' parameter is required");
+ return;
+ }
+
+ // If input is from a Tool Picker node it carries { "tool": "...", "args": {...} }
+ // — use those values when the param isn't explicitly set.
+ QJsonObject input_obj;
+ if (!inputs.isEmpty() && inputs[0].isObject())
+ input_obj = inputs[0].toObject();
+
+ if (tool.isEmpty())
+ tool = input_obj.value("tool").toString().trimmed();
+ if (tool.isEmpty()) {
+ cb(false, {}, "MCP Tool: no tool selected — set the 'Tool' param or connect a Tool Picker node");
+ return;
+ }
+
+ // Args: prefer "args" sub-object from Tool Picker, else pass the whole input object
+ QJsonObject args;
+ if (input_obj.contains("args") && input_obj.value("args").isObject())
+ args = input_obj.value("args").toObject();
+ else if (!input_obj.contains("tool"))
+ args = input_obj; // plain data input, not a Tool Picker output
+
+ (void)QtConcurrent::run([tool, args, cb]() {
+ auto& svc = mcp::McpService::instance();
+ mcp::ToolResult result;
+
+ // Support both "serverId__toolName" and bare tool name
+ if (tool.contains("__")) {
+ result = svc.execute_openai_function(tool, args);
+ } else {
+ result = svc.execute_tool(mcp::INTERNAL_SERVER_ID, tool, args);
+ }
+
+ if (!result.success) {
+ cb(false, {}, result.error.isEmpty() ? "MCP tool failed" : result.error);
+ return;
+ }
+
+ // Return the result data; wrap primitive values in an object
+ QJsonValue out = result.data.isNull() || result.data.isUndefined()
+ ? QJsonValue(result.to_json())
+ : result.data;
+ cb(true, out, {});
+ LOG_DEBUG("McpBridge", QString("Tool '%1' executed successfully").arg(tool));
+ });
+ };
+
+ LOG_INFO("ServiceBridges", "MCP bridge wired");
+}
+
void wire_all_bridges(NodeRegistry& registry) {
+ wire_mcp_bridges(registry);
wire_market_data_bridges(registry);
wire_trading_bridges(registry);
wire_agent_bridges(registry);
diff --git a/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp b/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp
index 37351c24d..97890f511 100644
--- a/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/AgentNodes.cpp
@@ -1,162 +1,270 @@
#include "services/workflow/nodes/AgentNodes.h"
+#include "ai_chat/LlmService.h"
+#include "mcp/McpService.h"
+#include "services/agents/AgentService.h"
+#include "services/agents/AgentTypes.h"
#include "services/workflow/NodeRegistry.h"
+#include "storage/repositories/AgentConfigRepository.h"
+#include "storage/repositories/LlmProfileRepository.h"
+
+#include <QJsonDocument>
+#include <QObject>
+#include <QUuid>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::workflow {
+// Serialise an input QJsonValue to a readable string for injecting into prompts.
+static QString json_to_context(const QJsonValue& v) {
+ if (v.isString()) return v.toString();
+ if (v.isDouble()) return QString::number(v.toDouble());
+ if (v.isBool()) return v.toBool() ? "true" : "false";
+ if (v.isObject()) return QString::fromUtf8(QJsonDocument(v.toObject()).toJson(QJsonDocument::Compact));
+ if (v.isArray()) return QString::fromUtf8(QJsonDocument(v.toArray()).toJson(QJsonDocument::Compact));
+ return {};
+}
+
void register_agent_nodes(NodeRegistry& registry) {
+
+ // ── Single unified AI Agent node ───────────────────────────────
+ // Parameters are populated dynamically at property-panel render time.
+ // The node stores agent_id + llm_profile_id; at execute time it:
+ // 1. Loads the AgentConfig from the repository by agent_id
+ // 2. Resolves the LLM profile by llm_profile_id (or falls back to
+ // the agent's saved assignment → global default)
+ // 3. Builds the same config JSON that AgentsViewPanel does
+ // 4. Calls AgentService::run_agent() and bridges the async
+ // agent_result signal back to the workflow callback via a
+ // one-shot QObject connection guarded by request_id
+
registry.register_type({
- .type_id = "agent.single",
+ .type_id = "agent.run",
.display_name = "AI Agent",
- .category = "Agents",
- .description = "Execute a single AI agent with a prompt",
- .icon_text = "AI",
+ .category = "Agents",
+ .description = "Run a configured AI agent with optional context input",
+ .icon_text = "AI",
.accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
+ .version = 2,
+ .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
.outputs = {{"output_main", "Response", PortDirection::Output, ConnectionType::Main}},
.parameters =
{
- {"agent_type",
- "Agent",
- "select",
- "general",
- {"general", "geopolitics", "economic", "hedge_fund", "trader", "investor", "deep_research"},
- "",
- true},
- {"prompt", "Prompt", "code", "", {}, "Instructions for the agent", true},
- {"model",
- "Model",
- "select",
- "auto",
- {"auto", "claude-sonnet-4-5-20250514", "claude-3-haiku-20240307", "gpt-4o", "gpt-4o-mini"},
- ""},
- {"max_tokens", "Max Tokens", "number", 4096, {}, ""},
+ // agent_id: populated as a "select" in the properties panel by querying
+ // AgentConfigRepository at render time via the ServiceBridges post-register
+ // hook. Stored as the agent UUID so the execute lambda can reload it.
+ {"agent_id", "Agent", "agent_select", "", {}, "Select a configured agent"},
+ {"llm_profile_id", "LLM Profile", "llm_select", "", {}, "Override LLM profile (leave blank to use agent default)"},
+ {"extra_instructions", "Extra Instructions", "code", "", {}, "Append additional instructions to the agent's system prompt"},
+ {"reasoning", "Extended Thinking", "boolean", false, {}, ""},
+ {"memory", "Memory", "boolean", false, {}, ""},
+ {"knowledge", "Knowledge Base", "boolean", false, {}, ""},
+ {"guardrails", "Guardrails", "boolean", false, {}, ""},
},
- .execute = nullptr, // Via AgentService
- });
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
- registry.register_type({
- .type_id = "agent.multi",
- .display_name = "Multi-Agent",
- .category = "Agents",
- .description = "Run multiple AI agents in parallel",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Combined", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"agents", "Agent Types", "string", "economic,geopolitics", {}, "Comma-separated agent types"},
- {"prompt", "Shared Prompt", "code", "", {}, "Prompt sent to all agents"},
- },
- .execute = nullptr,
- });
+ QString agent_id = params.value("agent_id").toString();
+ QString profile_id = params.value("llm_profile_id").toString();
+ QString extra_instr = params.value("extra_instructions").toString();
- registry.register_type({
- .type_id = "agent.mediator",
- .display_name = "Agent Mediator",
- .category = "Agents",
- .description = "Coordinate multiple agents (sequential, parallel, consensus)",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs =
- {
- {"input_0", "Agent 1", PortDirection::Input, ConnectionType::Main},
- {"input_1", "Agent 2", PortDirection::Input, ConnectionType::Main},
- },
- .outputs = {{"output_main", "Mediated", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"mode", "Mode", "select", "sequential", {"sequential", "parallel", "consensus", "debate"}, ""},
- {"mediator_prompt", "Mediator Prompt", "code", "", {}, "Instructions for the mediator"},
- },
- .execute = nullptr,
- });
+ // Load agent config from DB
+ QString instructions;
+ QJsonArray tools;
+ if (!agent_id.isEmpty()) {
+ auto res = fincept::AgentConfigRepository::instance().get(agent_id);
+ if (res.is_ok()) {
+ auto cfg_json = QJsonDocument::fromJson(
+ res.value().config_json.toUtf8()).object();
+ instructions = cfg_json.value("instructions").toString();
+ tools = cfg_json.value("tools").toArray();
+ }
+ }
- // ── Tier 3: AI nodes ───────────────────────────────────────────
+ if (!extra_instr.isEmpty()) {
+ instructions = instructions.isEmpty()
+ ? extra_instr
+ : instructions + "\n\n" + extra_instr;
+ }
- registry.register_type({
- .type_id = "agent.summarizer",
- .display_name = "Summarizer",
- .category = "Agents",
- .description = "Summarize long text, data, or documents",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Text In", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Summary", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"max_length", "Max Length", "number", 500, {}, "Max summary words"},
- {"style", "Style", "select", "concise", {"concise", "detailed", "bullet_points", "executive"}, ""},
- {"model",
- "Model",
- "select",
- "auto",
- {"auto", "claude-sonnet-4-5-20250514", "claude-3-haiku-20240307", "gpt-4o", "gpt-4o-mini"},
- ""},
- },
- .execute = nullptr,
- });
+ // Resolve LLM profile
+ using fincept::ai_chat::LlmService;
+ using fincept::LlmProfileRepository;
+ using fincept::ResolvedLlmProfile;
- registry.register_type({
- .type_id = "agent.classifier",
- .display_name = "Classifier",
- .category = "Agents",
- .description = "Classify text (bullish/bearish/neutral, sector, topic)",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Text In", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Classification", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"categories", "Categories", "string", "bullish,bearish,neutral", {}, "Comma-separated"},
- {"multi_label", "Multi-Label", "boolean", false, {}, "Allow multiple categories"},
- {"confidence_threshold", "Min Confidence", "number", 0.7, {}, ""},
+ ResolvedLlmProfile resolved;
+ if (!profile_id.isEmpty()) {
+ auto pr = LlmProfileRepository::instance().list_profiles();
+ if (pr.is_ok()) {
+ for (const auto& p : pr.value()) {
+ if (p.id == profile_id) {
+ resolved.profile_id = p.id;
+ resolved.profile_name = p.name;
+ resolved.provider = p.provider;
+ resolved.model_id = p.model_id;
+ resolved.api_key = p.api_key;
+ resolved.base_url = p.base_url;
+ resolved.temperature = p.temperature;
+ resolved.max_tokens = p.max_tokens;
+ resolved.system_prompt = p.system_prompt;
+ break;
+ }
+ }
+ }
+ }
+ if (resolved.provider.isEmpty())
+ resolved = LlmService::instance().resolve_profile("agent", agent_id);
+
+ // Build config (mirrors AgentsViewPanel::build_config_from_editor)
+ QJsonObject config;
+ config["model"] = LlmService::profile_to_json(resolved);
+ config["instructions"] = instructions;
+ config["tools"] = tools;
+ config["reasoning"] = params.value("reasoning").toBool(false);
+ config["memory"] = params.value("memory").toBool(false);
+ config["knowledge"] = params.value("knowledge").toBool(false);
+ config["guardrails"] = params.value("guardrails").toBool(false);
+ config["tracing"] = false;
+ config["agentic_memory"] = false;
+
+ // Build query — prepend upstream context if any
+ QString query;
+ if (!inputs.isEmpty() && !inputs[0].isNull() && !inputs[0].isUndefined()) {
+ QString ctx = json_to_context(inputs[0]);
+ if (!ctx.isEmpty())
+ query = "Context:\n" + ctx + "\n\n";
+ }
+ if (!instructions.isEmpty() && query.isEmpty())
+ query = instructions;
+ else if (!instructions.isEmpty())
+ query += instructions;
+
+ if (query.trimmed().isEmpty()) {
+ cb(false, {}, "No prompt or instructions — set Extra Instructions or configure the agent");
+ return;
+ }
+
+ auto& svc = fincept::services::AgentService::instance();
+
+ // Run agent — result comes back via agent_result signal.
+ // Connect a one-shot lambda guarded by request_id to avoid
+ // cross-workflow contamination.
+ QString req_id = svc.run_agent(query, config);
+
+ // Bridge the signal to the workflow callback.
+ // QObject::connect with a lambda capture; the connection is
+ // stored and disconnected after first matching result.
+ struct Guard : QObject {
+ std::function<void(bool, QJsonValue, QString)> cb;
+ QString req_id;
+ QMetaObject::Connection conn;
+ };
+ auto* guard = new Guard;
+ guard->cb = cb;
+ guard->req_id = req_id;
+ guard->conn = QObject::connect(
+ &svc, &fincept::services::AgentService::agent_result,
+ guard,
+ [guard](const fincept::services::AgentExecutionResult& result) {
+ if (result.request_id != guard->req_id) return;
+ QObject::disconnect(guard->conn);
+ guard->deleteLater();
+ if (!result.success) {
+ guard->cb(false, {}, result.error.isEmpty()
+ ? "Agent execution failed" : result.error);
+ return;
+ }
+ QJsonObject out;
+ out["response"] = result.response;
+ out["agent_id"] = guard->req_id.left(8);
+ out["exec_ms"] = result.execution_time_ms;
+ guard->cb(true, out, {});
+ });
},
- .execute = nullptr,
});
+ // ── Tool Picker ────────────────────────────────────────────────
+ // Takes a natural-language query (or upstream JSON context), asks the
+ // configured LLM which Fincept MCP tool best handles the request, and
+ // outputs { "tool": "<name>", "args": {...} } ready for the MCP Tool node.
registry.register_type({
- .type_id = "agent.code_generator",
- .display_name = "Code Generator",
- .category = "Agents",
- .description = "Generate Python/SQL code from natural language",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Code", PortDirection::Output, ConnectionType::Main}},
+ .type_id = "agent.tool_picker",
+ .display_name = "Tool Picker",
+ .category = "Agents",
+ .description = "Ask the LLM to pick the right MCP tool and arguments for a query",
+ .icon_text = "TP",
+ .accent_color = "#6366f1",
+ .version = 1,
+ .inputs = {{"input_0", "Query / Context", PortDirection::Input, ConnectionType::Main}},
+ .outputs = {{"output_main", "Tool Call", PortDirection::Output, ConnectionType::Main}},
.parameters =
{
- {"language", "Language", "select", "python", {"python", "sql", "javascript", "r"}, ""},
- {"prompt", "Prompt", "code", "", {}, "Describe what code to generate", true},
- {"execute_code", "Auto-Execute", "boolean", false, {}, "Run generated code immediately"},
+ {"query", "Query", "string", "", {}, "What do you want to do? (overrides input)", false},
},
- .execute = nullptr,
- });
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
- registry.register_type({
- .type_id = "agent.rag_query",
- .display_name = "RAG Query",
- .category = "Agents",
- .description = "Query against document embeddings (RAG)",
- .icon_text = "AI",
- .accent_color = "#7c3aed",
- .version = 1,
- .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Answer", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"query", "Query", "string", "", {}, "Question to ask", true},
- {"collection", "Collection", "string", "default", {}, "Document collection name"},
- {"top_k", "Top K Results", "number", 5, {}, ""},
+ // Build the user query — explicit param wins, else upstream input
+ QString query = params.value("query").toString().trimmed();
+ if (query.isEmpty() && !inputs.isEmpty() && !inputs[0].isNull()) {
+ query = json_to_context(inputs[0]);
+ }
+ if (query.isEmpty()) {
+ cb(false, {}, "Tool Picker: provide a query via the 'Query' param or an upstream input");
+ return;
+ }
+
+ // Build tool catalogue summary for the prompt
+ auto tools = mcp::McpService::instance().get_all_tools();
+ QString tool_list;
+ for (const auto& t : tools) {
+ tool_list += QString("- %1: %2\n").arg(t.name, t.description);
+ }
+
+ QString system_prompt =
+ "You are a tool-selection assistant for the Fincept Terminal.\n"
+ "Given a user request, choose the single best tool from the list below "
+ "and return ONLY a JSON object with this exact shape:\n"
+ "{\"tool\": \"<tool_name>\", \"args\": {<required args as key/value>}}\n"
+ "Do not include any explanation or markdown. Return raw JSON only.\n\n"
+ "Available tools:\n" + tool_list;
+
+ (void)QtConcurrent::run([system_prompt, query, cb]() {
+ using fincept::ai_chat::LlmService;
+ using fincept::ai_chat::ConversationMessage;
+
+ // Single non-streaming call using globally active LLM config
+ auto resp = LlmService::instance().chat(
+ query,
+ {ConversationMessage{"system", system_prompt}});
+
+ if (!resp.success) {
+ cb(false, {}, "Tool Picker LLM call failed: " + resp.error);
+ return;
+ }
+
+ // Strip markdown fences if model wraps output
+ QString raw = resp.content.trimmed();
+ if (raw.startsWith("```"))
+ raw = raw.section('\n', 1).section("```", 0, 0).trimmed();
+
+ auto doc = QJsonDocument::fromJson(raw.toUtf8());
+ if (doc.isNull() || !doc.isObject()) {
+ cb(false, {}, "Tool Picker: LLM did not return valid JSON: " + raw.left(200));
+ return;
+ }
+
+ QJsonObject out = doc.object();
+ if (!out.contains("tool")) {
+ cb(false, {}, "Tool Picker: JSON missing 'tool' key: " + raw.left(200));
+ return;
+ }
+
+ cb(true, out, {});
+ });
},
- .execute = nullptr,
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
index 8636a0ddb..2e4745393 100644
--- a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
@@ -1,9 +1,48 @@
#include "services/workflow/nodes/AnalyticsNodes.h"
#include "services/workflow/NodeRegistry.h"
+#include "python/PythonRunner.h"
+
+#include <QJsonDocument>
namespace fincept::workflow {
+using fincept::python::PythonRunner;
+using fincept::python::PythonResult;
+using fincept::python::extract_json;
+
+namespace {
+
+// Helper: run a Python script and parse the JSON result.
+void analytics_run_python_json(const QString& script, const QStringList& args,
+ std::function<void(bool, QJsonValue, QString)> cb)
+{
+ PythonRunner::instance().run(script, args, [cb](const PythonResult& res) {
+ if (!res.success) {
+ cb(false, {}, res.error);
+ return;
+ }
+ QString json_str = extract_json(res.output).trimmed();
+ auto doc = QJsonDocument::fromJson(json_str.toUtf8());
+ if (doc.isNull()) {
+ cb(false, {}, "Invalid JSON: " + res.output.left(200));
+ return;
+ }
+ cb(true, doc.isObject() ? QJsonValue(doc.object()) : QJsonValue(doc.array()), {});
+ });
+}
+
+// Helper: produce a clear "not yet implemented" result object.
+QJsonValue analytics_not_implemented(const QString& type_id)
+{
+ QJsonObject obj;
+ obj["error"] = "not_yet_implemented";
+ obj["node"] = type_id;
+ return obj;
+}
+
+} // anonymous namespace
+
void register_analytics_nodes(NodeRegistry& registry) {
registry.register_type({
.type_id = "analytics.technical_indicators",
@@ -27,7 +66,31 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"period", "Period", "number", 14, {}, "Lookback period"},
{"symbol", "Symbol", "string", "", {}, "Ticker symbol"},
},
- .execute = nullptr, // Via PythonRunner
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ // Serialise input price data to pass as a JSON string arg.
+ QJsonValue input_val = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ QJsonDocument input_doc;
+ if (input_val.isArray())
+ input_doc = QJsonDocument(input_val.toArray());
+ else if (input_val.isObject())
+ input_doc = QJsonDocument(input_val.toObject());
+
+ QString json_data = input_doc.isNull()
+ ? "{}"
+ : QString::fromUtf8(input_doc.toJson(QJsonDocument::Compact));
+
+ QString indicator = params.value("indicator").toString("SMA");
+ QString period = QString::number(static_cast<int>(params.value("period").toDouble(14)));
+ QString symbol = params.value("symbol").toString();
+
+ QStringList args = {"--data", json_data, "--indicator", indicator, "--period", period};
+ if (!symbol.isEmpty())
+ args << "--symbol" << symbol;
+
+ analytics_run_python_json("compute_technicals.py", args, cb);
+ },
});
registry.register_type({
@@ -47,7 +110,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"initial_capital", "Initial Capital", "number", 100000, {}, ""},
{"commission", "Commission %", "number", 0.001, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.backtest"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -70,7 +137,21 @@ void register_analytics_nodes(NodeRegistry& registry) {
""},
{"risk_free_rate", "Risk-Free Rate", "number", 0.05, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ // Build a JSON args object containing the input data and params.
+ QJsonObject args_obj;
+ args_obj["method"] = params.value("method").toString("mean_variance");
+ args_obj["risk_free_rate"] = params.value("risk_free_rate").toDouble(0.05);
+ if (!inputs.isEmpty())
+ args_obj["holdings"] = inputs[0];
+
+ QString json_args = QString::fromUtf8(
+ QJsonDocument(args_obj).toJson(QJsonDocument::Compact));
+
+ analytics_run_python_json("optimize_portfolio_weights.py", {"--args", json_args}, cb);
+ },
});
registry.register_type({
@@ -88,7 +169,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"benchmark", "Benchmark", "string", "SPY", {}, "Benchmark symbol"},
{"risk_free_rate", "Risk-Free Rate", "number", 0.05, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.performance_metrics"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -106,7 +191,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"method", "Method", "select", "pearson", {"pearson", "spearman", "kendall"}, ""},
{"period", "Period", "string", "1y", {}, "Lookback period"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.correlation_matrix"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -130,7 +219,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"confidence", "Confidence Level", "number", 0.95, {}, ""},
{"horizon", "Horizon (days)", "number", 1, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.risk_analysis"), "not_yet_implemented");
+ },
});
// ── Tier 1 additions ───────────────────────────────────────────
@@ -151,7 +244,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"risk_free_rate", "Risk-Free Rate", "number", 0.05, {}, ""},
{"benchmark", "Benchmark", "string", "SPY", {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.sharpe_ratio"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -174,7 +271,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"slow_period", "Slow MA Period", "number", 200, {}, ""},
{"ma_type", "MA Type", "select", "SMA", {"SMA", "EMA", "WMA"}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.ma_crossover"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -191,7 +292,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{
{"window", "Window", "string", "all", {}, "'all' or number of days"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.drawdown"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -210,7 +315,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"horizon_days", "Horizon (days)", "number", 252, {}, ""},
{"confidence", "Confidence Levels", "string", "0.95,0.99", {}, "Comma-separated"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.monte_carlo"), "not_yet_implemented");
+ },
});
// ── Tier 3: Advanced Analytics ─────────────────────────────────
@@ -230,7 +339,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"model", "Model", "select", "ff3", {"ff3", "ff5", "capm", "carhart4"}, ""},
{"period", "Period", "string", "3y", {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.factor_model"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -254,7 +367,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"lookback", "Lookback Days", "number", 60, {}, ""},
{"z_threshold", "Z-Score Threshold", "number", 2.0, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.pairs_trading"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -272,7 +389,11 @@ void register_analytics_nodes(NodeRegistry& registry) {
{"n_regimes", "Number of Regimes", "number", 3, {}, ""},
{"method", "Method", "select", "hmm", {"hmm", "rolling_vol", "trend_following"}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, analytics_not_implemented("analytics.regime_detection"), "not_yet_implemented");
+ },
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/ControlFlowNodes.cpp b/fincept-qt/src/services/workflow/nodes/ControlFlowNodes.cpp
index dacb413a6..f538d91b1 100644
--- a/fincept-qt/src/services/workflow/nodes/ControlFlowNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/ControlFlowNodes.cpp
@@ -4,6 +4,7 @@
#include "services/workflow/NodeRegistry.h"
#include <QTimer>
+#include <QJsonArray>
namespace fincept::workflow {
@@ -34,9 +35,32 @@ void register_control_flow_nodes(NodeRegistry& registry) {
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- Q_UNUSED(params);
- // Simplified: always routes to first output
- cb(true, data, {});
+ QString field = params.value("field").toString();
+ QString case1 = params.value("case1").toString();
+ QString case2 = params.value("case2").toString();
+
+ // Extract the field value from the input object
+ QString actual;
+ if (!field.isEmpty() && data.isObject())
+ actual = data.toObject().value(field).toVariant().toString();
+ else if (data.isString())
+ actual = data.toString();
+ else
+ actual = QString::number(data.toDouble());
+
+ // Route: case1 → output_0, case2 → output_1, else → output_2 (default)
+ // The workflow executor uses the first output by default; we encode
+ // the route index in the result so ExecutionResultsPanel can show it.
+ // Actual port routing requires WorkflowExecutor support — we annotate
+ // the output with "_route" so downstream can branch.
+ QJsonObject out = data.isObject() ? data.toObject() : QJsonObject{{"value", data}};
+ if (!case1.isEmpty() && actual == case1)
+ out["_route"] = 0;
+ else if (!case2.isEmpty() && actual == case2)
+ out["_route"] = 1;
+ else
+ out["_route"] = 2;
+ cb(true, out, {});
},
});
diff --git a/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp b/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
index afdbaa772..e441548f5 100644
--- a/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
@@ -2,8 +2,28 @@
#include "services/workflow/NodeRegistry.h"
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QRegularExpression>
+
namespace fincept::workflow {
+namespace {
+
+// Resolve a dot-notation path (e.g. "data.price") through a QJsonObject.
+QJsonValue resolve_dot_path(const QJsonObject& root, const QString& path)
+{
+ QStringList parts = path.split('.', Qt::SkipEmptyParts);
+ QJsonValue current = root;
+ for (const QString& part : parts) {
+ if (!current.isObject()) return QJsonValue{};
+ current = current.toObject().value(part);
+ }
+ return current;
+}
+
+} // anonymous namespace
+
void register_data_format_nodes(NodeRegistry& registry) {
registry.register_type({
.type_id = "format.json",
@@ -23,9 +43,73 @@ void register_data_format_nodes(NodeRegistry& registry) {
.execute =
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- Q_UNUSED(params);
- cb(true, data, {});
+ QJsonValue input = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ QString op = params.value("operation").toString("parse");
+
+ if (op == "stringify") {
+ // Convert the input value to a compact JSON string.
+ QJsonDocument doc;
+ if (input.isObject()) doc = QJsonDocument(input.toObject());
+ else if (input.isArray()) doc = QJsonDocument(input.toArray());
+ else {
+ // Scalar — wrap in a one-field object.
+ QJsonObject wrapper;
+ wrapper["value"] = input;
+ doc = QJsonDocument(wrapper);
+ }
+ QJsonObject out;
+ out["json_string"] = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
+ cb(true, out, {});
+ return;
+ }
+
+ if (op == "parse") {
+ // If input is already an object/array pass it through;
+ // if it is a string, parse it as JSON.
+ if (input.isObject() || input.isArray()) {
+ cb(true, input, {});
+ return;
+ }
+ // Try to find a string value: direct string or object with "text"/"json_string" key.
+ QString raw;
+ if (input.isString()) {
+ raw = input.toString();
+ } else if (input.isObject()) {
+ QJsonObject obj = input.toObject();
+ raw = obj.value("text").toString(obj.value("json_string").toString());
+ }
+ if (raw.isEmpty()) {
+ cb(false, {}, "format.json parse: no string input to parse");
+ return;
+ }
+ auto doc = QJsonDocument::fromJson(raw.toUtf8());
+ if (doc.isNull()) {
+ cb(false, {}, "format.json parse: invalid JSON");
+ return;
+ }
+ cb(true, doc.isObject() ? QJsonValue(doc.object()) : QJsonValue(doc.array()), {});
+ return;
+ }
+
+ if (op == "query") {
+ // Dot-notation path extraction.
+ QString path = params.value("query").toString();
+ // Strip leading "$." or "$" sentinel.
+ if (path.startsWith("$.")) path = path.mid(2);
+ else if (path == "$") { cb(true, input, {}); return; }
+
+ if (!input.isObject()) {
+ cb(false, {}, "format.json query: input must be an object");
+ return;
+ }
+ QJsonObject out;
+ out["result"] = resolve_dot_path(input.toObject(), path);
+ cb(true, out, {});
+ return;
+ }
+
+ // Unknown operation — pass through.
+ cb(true, input, {});
},
});
@@ -93,10 +177,62 @@ void register_data_format_nodes(NodeRegistry& registry) {
{"key_field", "Key Field", "string", "id", {}, "Field to match records by"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonArray arr_a = (inputs.size() > 0 && inputs[0].isArray())
+ ? inputs[0].toArray() : QJsonArray{};
+ QJsonArray arr_b = (inputs.size() > 1 && inputs[1].isArray())
+ ? inputs[1].toArray() : QJsonArray{};
+
+ QString key_field = params.value("key_field").toString("id");
+
+ // Build maps keyed by key_field value.
+ QHash<QString, QJsonObject> map_a, map_b;
+ for (const QJsonValue& item : arr_a) {
+ if (!item.isObject()) continue;
+ map_a.insert(item.toObject().value(key_field).toVariant().toString(),
+ item.toObject());
+ }
+ for (const QJsonValue& item : arr_b) {
+ if (!item.isObject()) continue;
+ map_b.insert(item.toObject().value(key_field).toVariant().toString(),
+ item.toObject());
+ }
+
+ QJsonArray added, removed, changed;
+
+ // Items in B but not A → added.
+ for (auto it = map_b.cbegin(); it != map_b.cend(); ++it) {
+ if (!map_a.contains(it.key()))
+ added.append(it.value());
+ }
+ // Items in A but not B → removed.
+ for (auto it = map_a.cbegin(); it != map_a.cend(); ++it) {
+ if (!map_b.contains(it.key()))
+ removed.append(it.value());
+ }
+ // Items in both but with different values → changed.
+ for (auto it = map_a.cbegin(); it != map_a.cend(); ++it) {
+ auto jt = map_b.find(it.key());
+ if (jt == map_b.end()) continue;
+ // Compact JSON comparison — field-order agnostic.
+ QByteArray doc_a = QJsonDocument(it.value()).toJson(QJsonDocument::Compact);
+ QByteArray doc_b = QJsonDocument(jt.value()).toJson(QJsonDocument::Compact);
+ if (doc_a != doc_b) {
+ QJsonObject diff;
+ diff["before"] = it.value();
+ diff["after"] = jt.value();
+ changed.append(diff);
+ }
+ }
+
+ // The node has three output ports; pack all results into one object
+ // so the WorkflowExecutor can fan them out to the correct ports.
+ QJsonObject out;
+ out["added"] = added;
+ out["removed"] = removed;
+ out["changed"] = changed;
+ cb(true, out, {});
},
});
@@ -119,9 +255,90 @@ void register_data_format_nodes(NodeRegistry& registry) {
{"encoding", "Encoding", "select", "utf-8", {"utf-8", "ascii", "latin-1"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ if (inputs.isEmpty()) { cb(false, {}, "format.csv_parse: no input"); return; }
+
+ // Accept either a raw string or an object with a "text" field.
+ QString csv_text;
+ QJsonValue input = inputs[0];
+ if (input.isString()) {
+ csv_text = input.toString();
+ } else if (input.isObject()) {
+ csv_text = input.toObject().value("text").toString(
+ input.toObject().value("content").toString());
+ }
+ if (csv_text.isEmpty()) {
+ cb(false, {}, "format.csv_parse: empty or non-string input");
+ return;
+ }
+
+ QString delim_param = params.value("delimiter").toString(",");
+ QChar delimiter = (delim_param == "\\t") ? '\t' : delim_param.at(0);
+ bool has_header = params.value("has_header").toBool(true);
+
+ // Split into lines, handling \r\n and \n.
+ QStringList lines = csv_text.split(QRegularExpression(R"(\r?\n)"), Qt::SkipEmptyParts);
+ if (lines.isEmpty()) { cb(true, QJsonArray{}, {}); return; }
+
+ // Helper: split a CSV line respecting double-quoted fields.
+ auto split_csv_line = [&](const QString& line) -> QStringList {
+ QStringList fields;
+ QString field;
+ bool in_quotes = false;
+ for (int i = 0; i < line.size(); ++i) {
+ QChar c = line[i];
+ if (c == '"') {
+ // Handle escaped quote ("") inside a quoted field.
+ if (in_quotes && i + 1 < line.size() && line[i + 1] == '"') {
+ field += '"';
+ ++i;
+ } else {
+ in_quotes = !in_quotes;
+ }
+ } else if (c == delimiter && !in_quotes) {
+ fields.append(field);
+ field.clear();
+ } else {
+ field += c;
+ }
+ }
+ fields.append(field);
+ return fields;
+ };
+
+ QJsonArray result;
+
+ if (has_header) {
+ QStringList headers = split_csv_line(lines[0]);
+ for (int row = 1; row < lines.size(); ++row) {
+ QStringList cols = split_csv_line(lines[row]);
+ QJsonObject obj;
+ for (int col = 0; col < headers.size(); ++col) {
+ QString val = (col < cols.size()) ? cols[col] : QString{};
+ // Try to parse as number; fall back to string.
+ bool ok = false;
+ double num = val.toDouble(&ok);
+ if (ok) obj.insert(headers[col], num);
+ else obj.insert(headers[col], val);
+ }
+ result.append(obj);
+ }
+ } else {
+ // No header: return array of arrays.
+ for (const QString& line : lines) {
+ QStringList cols = split_csv_line(line);
+ QJsonArray row_arr;
+ for (const QString& col : cols) {
+ bool ok = false;
+ double num = col.toDouble(&ok);
+ if (ok) row_arr.append(num);
+ else row_arr.append(col);
+ }
+ result.append(row_arr);
+ }
+ }
+ cb(true, result, {});
},
});
@@ -143,9 +360,69 @@ void register_data_format_nodes(NodeRegistry& registry) {
{"all_matches", "All Matches", "boolean", false, {}, "Return all matches as array"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ if (inputs.isEmpty()) { cb(false, {}, "format.regex_extract: no input"); return; }
+
+ QString pattern_str = params.value("pattern").toString();
+ if (pattern_str.isEmpty()) {
+ cb(false, {}, "format.regex_extract: pattern is required");
+ return;
+ }
+
+ QString field = params.value("field").toString("text");
+ int group = static_cast<int>(params.value("group").toDouble(0));
+ bool all_matches = params.value("all_matches").toBool(false);
+
+ // Extract source text from input.
+ QJsonValue input = inputs[0];
+ QString source_text;
+ if (input.isString()) {
+ source_text = input.toString();
+ } else if (input.isObject()) {
+ QJsonValue fv = input.toObject().value(field);
+ source_text = fv.isString() ? fv.toString() : QString::number(fv.toDouble());
+ }
+
+ QRegularExpression re(pattern_str);
+ if (!re.isValid()) {
+ cb(false, {}, "format.regex_extract: invalid regex: " + re.errorString());
+ return;
+ }
+
+ if (all_matches) {
+ QRegularExpressionMatchIterator it = re.globalMatch(source_text);
+ QJsonArray matches_arr;
+ while (it.hasNext()) {
+ QRegularExpressionMatch m = it.next();
+ int cap_count = m.lastCapturedIndex();
+ if (cap_count == 0 || group == 0) {
+ // Return full match string.
+ matches_arr.append(m.captured(0));
+ } else {
+ // Return requested capture group (if available).
+ matches_arr.append(group <= cap_count ? m.captured(group) : QString{});
+ }
+ }
+ cb(true, matches_arr, {});
+ } else {
+ QRegularExpressionMatch m = re.match(source_text);
+ if (!m.hasMatch()) {
+ QJsonObject out;
+ out["match"] = QJsonValue::Null;
+ out["groups"] = QJsonArray{};
+ cb(true, out, {});
+ return;
+ }
+ QJsonArray groups_arr;
+ for (int i = 1; i <= m.lastCapturedIndex(); ++i)
+ groups_arr.append(m.captured(i));
+
+ QJsonObject out;
+ out["match"] = m.captured(group <= m.lastCapturedIndex() ? group : 0);
+ out["groups"] = groups_arr;
+ cb(true, out, {});
+ }
},
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/FileNodes.cpp b/fincept-qt/src/services/workflow/nodes/FileNodes.cpp
index 62fbf1bff..c3bbfe463 100644
--- a/fincept-qt/src/services/workflow/nodes/FileNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/FileNodes.cpp
@@ -24,26 +24,6 @@ void register_file_nodes(NodeRegistry& registry) {
.execute = nullptr,
});
- registry.register_type({
- .type_id = "file.spreadsheet",
- .display_name = "Spreadsheet File",
- .category = "Files",
- .description = "Read/write Excel or CSV files",
- .icon_text = "F",
- .accent_color = "#525252",
- .version = 1,
- .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"operation", "Operation", "select", "read", {"read", "write"}, ""},
- {"path", "File Path", "string", "", {}, "", true},
- {"format", "Format", "select", "csv", {"csv", "xlsx", "tsv"}, ""},
- {"sheet", "Sheet Name", "string", "Sheet1", {}, "For Excel files"},
- },
- .execute = nullptr,
- });
-
registry.register_type({
.type_id = "file.binary",
.display_name = "Binary File",
diff --git a/fincept-qt/src/services/workflow/nodes/IntegrationNodes.cpp b/fincept-qt/src/services/workflow/nodes/IntegrationNodes.cpp
index 786acf9e7..80155f154 100644
--- a/fincept-qt/src/services/workflow/nodes/IntegrationNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/IntegrationNodes.cpp
@@ -1,49 +1,38 @@
#include "services/workflow/nodes/IntegrationNodes.h"
+#include "core/logging/Logger.h"
+#include "python/PythonRunner.h"
#include "services/workflow/NodeRegistry.h"
+using fincept::python::PythonRunner;
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QUrl>
+
namespace fincept::workflow {
void register_integration_nodes(NodeRegistry& registry) {
// ── MCP Tool Call ──────────────────────────────────────────────
+ // Single node that routes to any internal Fincept MCP tool.
+ // "tool" parameter accepts:
+ // - bare tool name (e.g. "get_quote") → routed to fincept-terminal server
+ // - "serverId__toolName" OpenAI function form → routed via execute_openai_function
registry.register_type({
.type_id = "mcp.tool_call",
.display_name = "MCP Tool",
- .category = "MCP Tools",
- .description = "Call any registered MCP server tool",
+ .category = "MCP",
+ .description = "Call any Fincept internal MCP tool by name",
.icon_text = "M",
.accent_color = "#6366f1",
- .version = 1,
- .inputs = {{"input_0", "Context", PortDirection::Input, ConnectionType::Main}},
+ .version = 2,
+ .inputs = {{"input_0", "Arguments", PortDirection::Input, ConnectionType::Main}},
.outputs = {{"output_main", "Result", PortDirection::Output, ConnectionType::Main}},
.parameters =
{
- {"server", "MCP Server", "string", "", {}, "Server name or URL", true},
- {"tool", "Tool Name", "string", "", {}, "Tool to invoke", true},
- {"arguments", "Arguments", "json", QJsonObject{}, {}, "Tool arguments as JSON"},
- {"timeout_sec", "Timeout (sec)", "number", 30, {}, ""},
+ {"tool", "Tool", "mcp_tool_select", "", {}, "", true},
},
- .execute = nullptr,
- });
-
- // ── Python Script ──────────────────────────────────────────────
- registry.register_type({
- .type_id = "mcp.python_script",
- .display_name = "Python Script",
- .category = "MCP Tools",
- .description = "Run a specific Python script from scripts/ directory",
- .icon_text = "M",
- .accent_color = "#6366f1",
- .version = 1,
- .inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
- .outputs = {{"output_main", "Result", PortDirection::Output, ConnectionType::Main}},
- .parameters =
- {
- {"script", "Script Path", "string", "", {}, "e.g. equity_talipp.py", true},
- {"function", "Function", "string", "main", {}, "Function to call"},
- {"args", "Arguments", "json", QJsonObject{}, {}, "Script arguments"},
- },
- .execute = nullptr,
+ .execute = nullptr, // wired in ServiceBridges::wire_all_bridges
});
// ── Push Notification ──────────────────────────────────────────
@@ -153,25 +142,65 @@ void register_integration_nodes(NodeRegistry& registry) {
.execute = nullptr,
});
- // ── Google Sheets ──────────────────────────────────────────────
+ // ── Spreadsheet (local xlsx/csv + Google Sheets via Python) ───────
registry.register_type({
.type_id = "utility.google_sheets",
- .display_name = "Google Sheets",
+ .display_name = "Spreadsheet",
.category = "Utilities",
- .description = "Read/write Google Sheets",
+ .description = "Read/write local .xlsx/.csv or Google Sheets (public/private)",
.icon_text = "#",
- .accent_color = "#808080",
- .version = 1,
+ .accent_color = "#16a34a",
+ .version = 3,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs = {{"output_main", "Main", PortDirection::Output, ConnectionType::Main}},
.parameters =
{
- {"operation", "Operation", "select", "read", {"read", "write", "append", "clear"}, ""},
- {"spreadsheet_id", "Spreadsheet ID", "string", "", {}, "Google Sheet ID", true},
- {"sheet_name", "Sheet Name", "string", "Sheet1", {}, ""},
- {"range", "Range", "string", "A1:Z1000", {}, "Cell range"},
+ {"source", "Source", "select", "local", {"local", "google"}, ""},
+ {"operation", "Operation", "select", "read", {"read", "write", "append", "clear"}, ""},
+ {"file_path", "File Path", "file_managed", "", {}, "xlsx,csv"},
+ {"spreadsheet_id", "Spreadsheet ID", "string", "", {}, "Google Sheet ID from URL (source=google)"},
+ {"sheet_name", "Sheet Name", "string", "Sheet1", {}, ""},
+ {"range", "Range", "string", "A1:Z1000", {}, "Cell range e.g. A1:D100"},
+ {"credentials_path", "Credentials JSON", "file_managed", "", {}, "json"},
+ },
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+
+ // Build args for spreadsheet.py
+ QJsonObject args;
+ args["source"] = params.value("source").toString("local");
+ args["operation"] = params.value("operation").toString("read");
+ args["file_path"] = params.value("file_path").toString();
+ args["spreadsheet_id"] = params.value("spreadsheet_id").toString();
+ args["sheet_name"] = params.value("sheet_name").toString("Sheet1");
+ args["range"] = params.value("range").toString("A1:Z1000");
+ args["credentials_path"] = params.value("credentials_path").toString();
+
+ // Attach input data for write/append operations
+ if (!inputs.isEmpty())
+ args["data"] = inputs[0];
+
+ QString args_json = QString::fromUtf8(
+ QJsonDocument(args).toJson(QJsonDocument::Compact));
+
+ PythonRunner::instance().run(
+ "spreadsheet.py", {"--args", args_json},
+ [cb](const fincept::python::PythonResult& res) {
+ if (!res.success) {
+ cb(false, {}, res.error.isEmpty() ? "spreadsheet.py failed" : res.error);
+ return;
+ }
+ QString out = fincept::python::extract_json(res.output).trimmed();
+ auto doc = QJsonDocument::fromJson(out.toUtf8());
+ if (doc.isNull()) { cb(false, {}, "Invalid JSON from spreadsheet.py: " + res.output.left(200)); return; }
+ if (doc.isObject() && doc.object().contains("error")) {
+ cb(false, {}, doc.object().value("error").toString());
+ return;
+ }
+ cb(true, doc.isObject() ? QJsonValue(doc.object()) : QJsonValue(doc.array()), {});
+ });
},
- .execute = nullptr,
});
// ── Generic API Call ───────────────────────────────────────────
diff --git a/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp b/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
index 003043444..080e5fefc 100644
--- a/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/MarketDataNodes.cpp
@@ -1,9 +1,48 @@
#include "services/workflow/nodes/MarketDataNodes.h"
#include "services/workflow/NodeRegistry.h"
+#include "python/PythonRunner.h"
+
+#include <QJsonDocument>
namespace fincept::workflow {
+using fincept::python::PythonRunner;
+using fincept::python::PythonResult;
+using fincept::python::extract_json;
+
+namespace {
+
+// Helper: run a Python script and parse the JSON result, calling cb with the outcome.
+void run_python_json(const QString& script, const QStringList& args,
+ std::function<void(bool, QJsonValue, QString)> cb)
+{
+ PythonRunner::instance().run(script, args, [cb](const PythonResult& res) {
+ if (!res.success) {
+ cb(false, {}, res.error);
+ return;
+ }
+ QString json_str = extract_json(res.output).trimmed();
+ auto doc = QJsonDocument::fromJson(json_str.toUtf8());
+ if (doc.isNull()) {
+ cb(false, {}, "Invalid JSON: " + res.output.left(200));
+ return;
+ }
+ cb(true, doc.isObject() ? QJsonValue(doc.object()) : QJsonValue(doc.array()), {});
+ });
+}
+
+// Helper: produce a clear "not yet implemented" result object.
+QJsonValue not_implemented(const QString& type_id)
+{
+ QJsonObject obj;
+ obj["error"] = "not_yet_implemented";
+ obj["node"] = type_id;
+ return obj;
+}
+
+} // anonymous namespace
+
void register_market_data_nodes(NodeRegistry& registry) {
registry.register_type({
.type_id = "market.get_quote",
@@ -20,7 +59,12 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"symbol", "Symbol", "string", "AAPL", {}, "Ticker symbol", true},
{"source", "Source", "select", "yahoo", {"yahoo", "alpha_vantage", "polygon", "databento"}, ""},
},
- .execute = nullptr, // Wired via MarketDataService
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString symbol = params.value("symbol").toString("AAPL");
+ run_python_json("yfinance_data.py", {"quote", symbol}, cb);
+ },
});
registry.register_type({
@@ -39,7 +83,14 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"period", "Period", "select", "1y", {"1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "max"}, ""},
{"interval", "Interval", "select", "1d", {"1m", "5m", "15m", "1h", "1d", "1wk", "1mo"}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString symbol = params.value("symbol").toString("AAPL");
+ QString period = params.value("period").toString("1y");
+ QString interval = params.value("interval").toString("1d");
+ run_python_json("yfinance_data.py", {"historical_period", symbol, period, interval}, cb);
+ },
});
registry.register_type({
@@ -57,7 +108,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"symbol", "Symbol", "string", "AAPL", {}, "Ticker symbol", true},
{"depth", "Depth", "number", 10, {}, "Number of levels"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_depth"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -74,7 +129,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{
{"symbol", "Symbol", "string", "AAPL", {}, "Ticker symbol", true},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_stats"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -92,7 +151,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"symbol", "Symbol", "string", "AAPL", {}, "Ticker symbol", true},
{"type", "Type", "select", "overview", {"overview", "income", "balance", "cashflow", "earnings"}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_fundamentals"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -115,7 +178,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
""},
{"country", "Country", "string", "US", {}, "Country code"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_economics"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -133,7 +200,13 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"symbol", "Symbol", "string", "", {}, "Optional ticker filter"},
{"limit", "Limit", "number", 10, {}, "Number of articles"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString symbol = params.value("symbol").toString();
+ QString limit = QString::number(static_cast<int>(params.value("limit").toDouble(10)));
+ run_python_json("yfinance_data.py", {"news", symbol, limit}, cb);
+ },
});
// ── Tier 1 additions ───────────────────────────────────────────
@@ -154,7 +227,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"expiry", "Expiry", "string", "", {}, "YYYY-MM-DD or 'nearest'"},
{"type", "Type", "select", "both", {"calls", "puts", "both"}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_options_chain"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -191,7 +268,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"base", "Base Currency", "string", "USD", {}, "", true},
{"quote", "Quote Currency", "string", "EUR", {}, "", true},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.get_forex_rate"), "not_yet_implemented");
+ },
});
// ── Tier 3: Advanced Market Data ───────────────────────────────
@@ -221,7 +302,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"country", "Country", "select", "US", {"US", "UK", "IN", "JP", "DE", "FR", "CA", "AU"}, ""},
{"limit", "Max Results", "number", 50, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.screener"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -241,7 +326,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
{"days_back", "Days Back", "number", 30, {}, ""},
{"min_value", "Min Transaction Value ($)", "number", 100000, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.insider_trades"), "not_yet_implemented");
+ },
});
registry.register_type({
@@ -265,7 +354,11 @@ void register_market_data_nodes(NodeRegistry& registry) {
""},
{"limit", "Limit", "number", 10, {}, ""},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject&, const QVector<QJsonValue>&,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ cb(false, not_implemented("market.sec_filings"), "not_yet_implemented");
+ },
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp b/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
index 6b203f180..0473e2802 100644
--- a/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
@@ -2,9 +2,18 @@
#include "services/workflow/NodeRegistry.h"
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonObject>
+#include <cmath>
+
namespace fincept::workflow {
void register_safety_nodes(NodeRegistry& registry) {
+
+ // ── Risk Check ────────────────────────────────────────────────
+ // Input: { symbol, quantity, price, portfolio_value, volatility }
+ // Checks position size % and volatility against thresholds.
registry.register_type({
.type_id = "safety.risk_check",
.display_name = "Risk Check",
@@ -12,7 +21,7 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Validate trade against position size and volatility limits",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Trade In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
@@ -22,17 +31,53 @@ void register_safety_nodes(NodeRegistry& registry) {
.parameters =
{
{"max_position_pct", "Max Position %", "number", 5.0, {}, "Max % of portfolio per position"},
- {"max_volatility", "Max Volatility", "number", 0.5, {}, "Max annualized volatility"},
+ {"max_volatility", "Max Volatility", "number", 0.5, {}, "Max annualized volatility (0-1)"},
},
.execute =
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- Q_UNUSED(params);
- cb(true, data, {}); // Placeholder: always passes
+ QJsonObject trade = data.isObject() ? data.toObject() : QJsonObject{};
+
+ double max_pos_pct = params.value("max_position_pct").toDouble(5.0);
+ double max_vol = params.value("max_volatility").toDouble(0.5);
+
+ double quantity = trade.value("quantity").toDouble(0);
+ double price = trade.value("price").toDouble(0);
+ double portfolio_value = trade.value("portfolio_value").toDouble(0);
+ double volatility = trade.value("volatility").toDouble(0);
+
+ QStringList failures;
+
+ if (portfolio_value > 0 && price > 0) {
+ double position_value = quantity * price;
+ double position_pct = (position_value / portfolio_value) * 100.0;
+ if (position_pct > max_pos_pct)
+ failures << QString("Position size %1% exceeds max %2%")
+ .arg(position_pct, 0, 'f', 2)
+ .arg(max_pos_pct, 0, 'f', 2);
+ }
+
+ if (volatility > 0 && volatility > max_vol)
+ failures << QString("Volatility %1 exceeds max %2")
+ .arg(volatility, 0, 'f', 3)
+ .arg(max_vol, 0, 'f', 3);
+
+ QJsonObject out = trade;
+ out["risk_check_passed"] = failures.isEmpty();
+ if (!failures.isEmpty()) {
+ QJsonArray fa;
+ for (const QString& f : failures) fa.append(f);
+ out["risk_failures"] = fa;
+ cb(false, out, failures.join("; "));
+ } else {
+ cb(true, out, {});
+ }
},
});
+ // ── Loss Limit ────────────────────────────────────────────────
+ // Input: { daily_pnl, weekly_pnl } — checks against configured limits.
registry.register_type({
.type_id = "safety.loss_limit",
.display_name = "Loss Limit",
@@ -40,26 +85,50 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Enforce daily/weekly loss limits",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
{"output_pass", "Under Limit", PortDirection::Output, ConnectionType::Main},
- {"output_fail", "Over Limit", PortDirection::Output, ConnectionType::Main},
+ {"output_fail", "Over Limit", PortDirection::Output, ConnectionType::Main},
},
.parameters =
{
- {"daily_limit", "Daily Loss Limit", "number", 1000, {}, "$ amount"},
+ {"daily_limit", "Daily Loss Limit", "number", 1000, {}, "$ amount"},
{"weekly_limit", "Weekly Loss Limit", "number", 5000, {}, "$ amount"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ double daily_limit = params.value("daily_limit").toDouble(1000);
+ double weekly_limit = params.value("weekly_limit").toDouble(5000);
+ double daily_pnl = obj.value("daily_pnl").toDouble(0);
+ double weekly_pnl = obj.value("weekly_pnl").toDouble(0);
+
+ QStringList failures;
+ if (-daily_pnl > daily_limit)
+ failures << QString("Daily loss $%1 exceeds limit $%2")
+ .arg(-daily_pnl, 0, 'f', 2).arg(daily_limit, 0, 'f', 2);
+ if (-weekly_pnl > weekly_limit)
+ failures << QString("Weekly loss $%1 exceeds limit $%2")
+ .arg(-weekly_pnl, 0, 'f', 2).arg(weekly_limit, 0, 'f', 2);
+
+ obj["loss_limit_passed"] = failures.isEmpty();
+ if (!failures.isEmpty()) {
+ QJsonArray fa; for (const QString& f : failures) fa.append(f);
+ obj["loss_failures"] = fa;
+ cb(false, obj, failures.join("; "));
+ } else {
+ cb(true, obj, {});
+ }
},
});
+ // ── Position Size Limit ───────────────────────────────────────
+ // Input: { quantity, price }
registry.register_type({
.type_id = "safety.position_size_limit",
.display_name = "Position Size Limit",
@@ -67,7 +136,7 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Enforce maximum position sizing",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
@@ -76,17 +145,41 @@ void register_safety_nodes(NodeRegistry& registry) {
},
.parameters =
{
- {"max_shares", "Max Shares", "number", 1000, {}, ""},
- {"max_value", "Max Value ($)", "number", 50000, {}, ""},
+ {"max_shares", "Max Shares", "number", 1000, {}, ""},
+ {"max_value", "Max Value ($)", "number", 50000, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ double max_shares = params.value("max_shares").toDouble(1000);
+ double max_value = params.value("max_value").toDouble(50000);
+ double quantity = obj.value("quantity").toDouble(0);
+ double price = obj.value("price").toDouble(0);
+ double trade_val = quantity * price;
+
+ QStringList failures;
+ if (quantity > max_shares)
+ failures << QString("Quantity %1 exceeds max %2").arg(quantity).arg(max_shares);
+ if (price > 0 && trade_val > max_value)
+ failures << QString("Trade value $%1 exceeds max $%2")
+ .arg(trade_val, 0, 'f', 2).arg(max_value, 0, 'f', 2);
+
+ obj["size_limit_passed"] = failures.isEmpty();
+ if (!failures.isEmpty()) {
+ QJsonArray fa; for (const QString& f : failures) fa.append(f);
+ obj["size_failures"] = fa;
+ cb(false, obj, failures.join("; "));
+ } else {
+ cb(true, obj, {});
+ }
},
});
+ // ── Trading Hours Check ───────────────────────────────────────
+ // Uses QDateTime in UTC to check exchange trading hours.
registry.register_type({
.type_id = "safety.trading_hours",
.display_name = "Trading Hours Check",
@@ -94,28 +187,66 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Validate trade is within market hours",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
- {"output_open", "Market Open", PortDirection::Output, ConnectionType::Main},
+ {"output_open", "Market Open", PortDirection::Output, ConnectionType::Main},
{"output_closed", "Market Closed", PortDirection::Output, ConnectionType::Main},
},
.parameters =
{
- {"exchange", "Exchange", "select", "NYSE", {"NYSE", "NASDAQ", "LSE", "TSE", "NSE", "BSE"}, ""},
- {"allow_premarket", "Allow Pre-Market", "boolean", false, {}, ""},
+ {"exchange", "Exchange", "select", "NYSE", {"NYSE", "NASDAQ", "LSE", "TSE", "NSE", "BSE"}, ""},
+ {"allow_premarket","Allow Pre-Market", "boolean", false, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ QString exchange = params.value("exchange").toString("NYSE");
+ bool allow_premarket = params.value("allow_premarket").toBool(false);
+
+ QDateTime utc_now = QDateTime::currentDateTimeUtc();
+ int day_of_week = utc_now.date().dayOfWeek(); // 1=Mon, 7=Sun
+ int hour_utc = utc_now.time().hour();
+ int min_utc = utc_now.time().minute();
+ int time_utc = hour_utc * 100 + min_utc;
+
+ // Weekend check (universal)
+ bool is_weekend = (day_of_week == 6 || day_of_week == 7);
+
+ // Session hours in UTC
+ // NYSE/NASDAQ: 14:30-21:00 UTC (pre-market 09:00-14:30)
+ // LSE: 08:00-16:30 UTC
+ // TSE (Tokyo): 00:00-06:00 UTC (09:00-15:00 JST)
+ // NSE/BSE (India): 03:45-10:00 UTC (09:15-15:30 IST)
+ struct Session { int open; int close; int pre_open; };
+ Session session{1430, 2100, 900};
+ if (exchange == "LSE") session = {800, 1630, 700};
+ else if (exchange == "TSE") session = {0, 600, 2300};
+ else if (exchange == "NSE" || exchange == "BSE") session = {345, 1000, 300};
+
+ bool in_regular = !is_weekend && time_utc >= session.open && time_utc < session.close;
+ bool in_premarket = !is_weekend && time_utc >= session.pre_open && time_utc < session.open;
+ bool is_open = in_regular || (allow_premarket && in_premarket);
+
+ obj["market_open"] = is_open;
+ obj["exchange"] = exchange;
+ obj["utc_time"] = utc_now.toString("HH:mm");
+ obj["session_type"] = in_regular ? "regular" : (in_premarket ? "pre_market" : "closed");
+
+ if (is_open)
+ cb(true, obj, {});
+ else
+ cb(false, obj, QString("Market closed: %1 UTC on %2")
+ .arg(utc_now.toString("HH:mm"), exchange));
},
});
- // ── Tier 1 additions ───────────────────────────────────────────
-
+ // ── Max Drawdown Check ────────────────────────────────────────
+ // Input: { peak_value, current_value } or { drawdown_pct }
registry.register_type({
.type_id = "safety.max_drawdown_check",
.display_name = "Max Drawdown Check",
@@ -123,26 +254,48 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Halt trading if drawdown exceeds threshold",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
{"output_pass", "Under Limit", PortDirection::Output, ConnectionType::Main},
- {"output_fail", "Exceeded", PortDirection::Output, ConnectionType::Main},
+ {"output_fail", "Exceeded", PortDirection::Output, ConnectionType::Main},
},
.parameters =
{
{"max_drawdown_pct", "Max Drawdown %", "number", 10.0, {}, ""},
- {"window", "Window", "select", "daily", {"daily", "weekly", "monthly", "ytd"}, ""},
+ {"window", "Window", "select", "daily", {"daily", "weekly", "monthly", "ytd"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ double max_dd = params.value("max_drawdown_pct").toDouble(10.0);
+
+ // Accept either drawdown_pct directly or peak/current values
+ double drawdown_pct = obj.value("drawdown_pct").toDouble(-1);
+ if (drawdown_pct < 0) {
+ double peak = obj.value("peak_value").toDouble(0);
+ double current = obj.value("current_value").toDouble(0);
+ drawdown_pct = (peak > 0) ? ((peak - current) / peak * 100.0) : 0;
+ }
+
+ obj["drawdown_pct"] = drawdown_pct;
+ obj["max_drawdown_pct"] = max_dd;
+ obj["drawdown_check_passed"]= drawdown_pct <= max_dd;
+
+ if (drawdown_pct > max_dd)
+ cb(false, obj, QString("Drawdown %1% exceeds max %2%")
+ .arg(drawdown_pct, 0, 'f', 2).arg(max_dd, 0, 'f', 2));
+ else
+ cb(true, obj, {});
},
});
+ // ── Correlation Check ─────────────────────────────────────────
+ // Input: { correlation } — checks against threshold.
registry.register_type({
.type_id = "safety.correlation_check",
.display_name = "Correlation Check",
@@ -150,26 +303,40 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Block trade if too correlated with existing positions",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
- {"output_pass", "Low Correlation", PortDirection::Output, ConnectionType::Main},
+ {"output_pass", "Low Correlation", PortDirection::Output, ConnectionType::Main},
{"output_fail", "High Correlation", PortDirection::Output, ConnectionType::Main},
},
.parameters =
{
{"max_correlation", "Max Correlation", "number", 0.8, {}, "0-1 threshold"},
- {"lookback_days", "Lookback Days", "number", 90, {}, ""},
+ {"lookback_days", "Lookback Days", "number", 90, {}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ double max_corr = params.value("max_correlation").toDouble(0.8);
+ double corr = std::abs(obj.value("correlation").toDouble(0));
+
+ obj["correlation_check_passed"] = corr <= max_corr;
+ obj["correlation_abs"] = corr;
+
+ if (corr > max_corr)
+ cb(false, obj, QString("Correlation %1 exceeds max %2")
+ .arg(corr, 0, 'f', 3).arg(max_corr, 0, 'f', 3));
+ else
+ cb(true, obj, {});
},
});
+ // ── Volatility Filter ─────────────────────────────────────────
+ // Input: { annualized_vol } or { vix }
registry.register_type({
.type_id = "safety.volatility_filter",
.display_name = "Volatility Filter",
@@ -177,24 +344,48 @@ void register_safety_nodes(NodeRegistry& registry) {
.description = "Skip trade if volatility is too high",
.icon_text = "!",
.accent_color = "#dc2626",
- .version = 1,
+ .version = 2,
.inputs = {{"input_0", "Data In", PortDirection::Input, ConnectionType::Main}},
.outputs =
{
{"output_pass", "Normal Vol", PortDirection::Output, ConnectionType::Main},
- {"output_fail", "High Vol", PortDirection::Output, ConnectionType::Main},
+ {"output_fail", "High Vol", PortDirection::Output, ConnectionType::Main},
},
.parameters =
{
{"max_annualized_vol", "Max Ann. Vol %", "number", 50.0, {}, ""},
- {"method", "Method", "select", "realized", {"realized", "implied", "vix_level"}, ""},
- {"vix_threshold", "VIX Threshold", "number", 30.0, {}, "For VIX method"},
+ {"method", "Method", "select", "realized", {"realized", "implied", "vix_level"}, ""},
+ {"vix_threshold", "VIX Threshold", "number", 30.0, {}, "For VIX method"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QJsonObject obj = data.isObject() ? data.toObject() : QJsonObject{};
+
+ QString method = params.value("method").toString("realized");
+ double max_vol = params.value("max_annualized_vol").toDouble(50.0);
+ double vix_threshold= params.value("vix_threshold").toDouble(30.0);
+
+ bool exceeded = false;
+ QString reason;
+
+ if (method == "vix_level") {
+ double vix = obj.value("vix").toDouble(0);
+ exceeded = vix > vix_threshold;
+ reason = QString("VIX %1 > threshold %2").arg(vix).arg(vix_threshold);
+ } else {
+ // realized or implied: expect annualized_vol as 0-100 percentage
+ double vol_pct = obj.value("annualized_vol").toDouble(0);
+ exceeded = vol_pct > max_vol;
+ reason = QString("Ann. vol %1% > max %2%").arg(vol_pct, 0, 'f', 1).arg(max_vol, 0, 'f', 1);
+ }
+
+ obj["volatility_check_passed"] = !exceeded;
+ if (exceeded)
+ cb(false, obj, reason);
+ else
+ cb(true, obj, {});
},
});
}
diff --git a/fincept-qt/src/services/workflow/nodes/UtilityNodes.cpp b/fincept-qt/src/services/workflow/nodes/UtilityNodes.cpp
index edc586508..b010ac2bc 100644
--- a/fincept-qt/src/services/workflow/nodes/UtilityNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/UtilityNodes.cpp
@@ -2,7 +2,12 @@
#include "services/workflow/NodeRegistry.h"
+#include <QCryptographicHash>
#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QRandomGenerator>
+#include <QRegularExpression>
namespace fincept::workflow {
@@ -62,10 +67,42 @@ void register_utility_nodes(NodeRegistry& registry) {
.execute =
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- // Pass through for now — full implementation in Phase 4
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- Q_UNUSED(params);
- cb(true, data, {});
+ if (inputs.isEmpty()) { cb(true, QJsonArray{}, {}); return; }
+
+ QString field = params.value("field").toString();
+ QString op = params.value("operator").toString("equals");
+ QString value = params.value("value").toString();
+
+ auto matches = [&](const QJsonValue& item) -> bool {
+ QJsonValue field_val = item.isObject() ? item.toObject().value(field) : QJsonValue{};
+ QString field_str = field_val.isString()
+ ? field_val.toString()
+ : QString::number(field_val.toDouble());
+
+ if (op == "equals") return field_str == value;
+ if (op == "not_equals") return field_str != value;
+ if (op == "contains") return field_str.contains(value, Qt::CaseInsensitive);
+ if (op == "greater_than") return field_val.toDouble() > value.toDouble();
+ if (op == "less_than") return field_val.toDouble() < value.toDouble();
+ return false;
+ };
+
+ QJsonValue input = inputs[0];
+
+ if (input.isArray()) {
+ QJsonArray src = input.toArray();
+ QJsonArray out;
+ for (const QJsonValue& item : src) {
+ if (matches(item))
+ out.append(item);
+ }
+ cb(true, out, {});
+ } else if (input.isObject()) {
+ // Treat the object itself as a single item.
+ cb(true, matches(input) ? input : QJsonValue(QJsonArray{}), {});
+ } else {
+ cb(true, input, {});
+ }
},
});
@@ -109,10 +146,45 @@ void register_utility_nodes(NodeRegistry& registry) {
{"operation", "Operation", "select", "sum", {"sum", "avg", "min", "max", "count"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ if (inputs.isEmpty() || !inputs[0].isArray()) {
+ cb(false, {}, "transform.aggregate requires a JSON array input");
+ return;
+ }
+
+ QString field = params.value("field").toString();
+ QString op = params.value("operation").toString("sum");
+ QJsonArray arr = inputs[0].toArray();
+
+ double result = 0.0;
+ double minimum = std::numeric_limits<double>::max();
+ double maximum = std::numeric_limits<double>::lowest();
+ int count = 0;
+
+ for (const QJsonValue& item : arr) {
+ if (!item.isObject()) continue;
+ QJsonValue fv = item.toObject().value(field);
+ double v = fv.toDouble();
+ result += v;
+ minimum = std::min(minimum, v);
+ maximum = std::max(maximum, v);
+ ++count;
+ }
+
+ double out_val = 0.0;
+ if (op == "sum") out_val = result;
+ else if (op == "avg") out_val = count > 0 ? result / count : 0.0;
+ else if (op == "min") out_val = count > 0 ? minimum : 0.0;
+ else if (op == "max") out_val = count > 0 ? maximum : 0.0;
+ else if (op == "count") out_val = static_cast<double>(count);
+
+ QJsonObject out;
+ out["result"] = out_val;
+ out["field"] = field;
+ out["operation"] = op;
+ out["count"] = count;
+ cb(true, out, {});
},
});
@@ -133,10 +205,45 @@ void register_utility_nodes(NodeRegistry& registry) {
{"direction", "Direction", "select", "asc", {"asc", "desc"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ if (inputs.isEmpty() || !inputs[0].isArray()) {
+ cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ return;
+ }
+
+ QString field = params.value("field").toString();
+ bool desc = params.value("direction").toString("asc") == "desc";
+
+ QJsonArray arr = inputs[0].toArray();
+ // Copy into a sortable list.
+ QVector<QJsonValue> items;
+ items.reserve(arr.size());
+ for (const QJsonValue& v : arr)
+ items.append(v);
+
+ std::stable_sort(items.begin(), items.end(),
+ [&](const QJsonValue& a, const QJsonValue& b) {
+ QJsonValue av = a.isObject() ? a.toObject().value(field) : QJsonValue{};
+ QJsonValue bv = b.isObject() ? b.toObject().value(field) : QJsonValue{};
+
+ // Numeric comparison if both are numbers.
+ if ((av.isDouble() || av.isUndefined()) &&
+ (bv.isDouble() || bv.isUndefined())) {
+ double da = av.toDouble();
+ double db = bv.toDouble();
+ return desc ? da > db : da < db;
+ }
+ // Fall back to string comparison.
+ QString sa = av.isString() ? av.toString() : QString::number(av.toDouble());
+ QString sb = bv.isString() ? bv.toString() : QString::number(bv.toDouble());
+ return desc ? sa > sb : sa < sb;
+ });
+
+ QJsonArray out;
+ for (const QJsonValue& v : items)
+ out.append(v);
+ cb(true, out, {});
},
});
@@ -161,10 +268,42 @@ void register_utility_nodes(NodeRegistry& registry) {
{"join_type", "Join Type", "select", "inner", {"inner", "left", "right", "outer"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ // Expect input_a at index 0, input_b at index 1.
+ QJsonArray arr_a = (inputs.size() > 0 && inputs[0].isArray())
+ ? inputs[0].toArray() : QJsonArray{};
+ QJsonArray arr_b = (inputs.size() > 1 && inputs[1].isArray())
+ ? inputs[1].toArray() : QJsonArray{};
+
+ QString join_key = params.value("join_key").toString("id");
+
+ // Build a lookup map from B keyed by join_key.
+ QHash<QString, QJsonObject> b_map;
+ for (const QJsonValue& item : arr_b) {
+ if (!item.isObject()) continue;
+ QJsonObject obj = item.toObject();
+ QString key_val = obj.value(join_key).toVariant().toString();
+ b_map.insert(key_val, obj);
+ }
+
+ // Inner join: only emit rows where key exists in both.
+ QJsonArray out;
+ for (const QJsonValue& item : arr_a) {
+ if (!item.isObject()) continue;
+ QJsonObject obj_a = item.toObject();
+ QString key_val = obj_a.value(join_key).toVariant().toString();
+ auto it = b_map.find(key_val);
+ if (it == b_map.end()) continue;
+
+ // Merge: B fields overwrite A on collision.
+ QJsonObject merged = obj_a;
+ const QJsonObject& obj_b = it.value();
+ for (auto bi = obj_b.begin(); bi != obj_b.end(); ++bi)
+ merged.insert(bi.key(), bi.value());
+ out.append(merged);
+ }
+ cb(true, out, {});
},
});
@@ -184,10 +323,32 @@ void register_utility_nodes(NodeRegistry& registry) {
{"field", "Group Field", "string", "", {}, "Field to group by", true},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ if (inputs.isEmpty() || !inputs[0].isArray()) {
+ cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ return;
+ }
+
+ QString field = params.value("field").toString();
+ QJsonArray arr = inputs[0].toArray();
+
+ // Preserve insertion order using a list of keys alongside the map.
+ QJsonObject groups;
+ QStringList key_order;
+
+ for (const QJsonValue& item : arr) {
+ if (!item.isObject()) continue;
+ QString group_val = item.toObject().value(field).toVariant().toString();
+ if (!groups.contains(group_val)) {
+ groups.insert(group_val, QJsonArray{});
+ key_order.append(group_val);
+ }
+ QJsonArray bucket = groups.value(group_val).toArray();
+ bucket.append(item);
+ groups.insert(group_val, bucket);
+ }
+ cb(true, groups, {});
},
});
@@ -207,10 +368,36 @@ void register_utility_nodes(NodeRegistry& registry) {
{"field", "Key Field", "string", "", {}, "Field to check for duplicates"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ if (inputs.isEmpty() || !inputs[0].isArray()) {
+ cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ return;
+ }
+
+ QString field = params.value("field").toString();
+ QJsonArray arr = inputs[0].toArray();
+ QJsonArray out;
+ QSet<QString> seen;
+
+ for (const QJsonValue& item : arr) {
+ QString key_val;
+ if (field.isEmpty()) {
+ // Whole-object dedup: use compact JSON as key.
+ QJsonDocument doc(item.toObject());
+ key_val = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
+ } else if (item.isObject()) {
+ key_val = item.toObject().value(field).toVariant().toString();
+ } else {
+ key_val = item.toVariant().toString();
+ }
+
+ if (!seen.contains(key_val)) {
+ seen.insert(key_val);
+ out.append(item);
+ }
+ }
+ cb(true, out, {});
},
});
@@ -230,10 +417,19 @@ void register_utility_nodes(NodeRegistry& registry) {
{"count", "Count", "number", 10, {}, "Max items to output"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ if (inputs.isEmpty()) { cb(true, QJsonArray{}, {}); return; }
+ if (!inputs[0].isArray()) { cb(true, inputs[0], {}); return; }
+
+ int n = static_cast<int>(params.value("count").toDouble(10));
+ if (n < 0) n = 0;
+
+ QJsonArray arr = inputs[0].toArray();
+ QJsonArray out;
+ for (int i = 0; i < n && i < arr.size(); ++i)
+ out.append(arr[i]);
+ cb(true, out, {});
},
});
@@ -259,10 +455,72 @@ void register_utility_nodes(NodeRegistry& registry) {
{"field", "Field", "string", "", {}, "Field to operate on"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QString op = params.value("operation").toString("split");
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+
+ // split: string → array by delimiter (field param used as delimiter)
+ if (op == "split") {
+ QString delim = params.value("field").toString(",");
+ if (delim.isEmpty()) delim = ",";
+ QString text = data.isString() ? data.toString()
+ : data.isObject() ? QString::fromUtf8(
+ QJsonDocument(data.toObject()).toJson(QJsonDocument::Compact))
+ : QString{};
+ QJsonArray out;
+ for (const QString& s : text.split(delim))
+ out.append(s.trimmed());
+ cb(true, out, {});
+ return;
+ }
+
+ // All remaining ops work on arrays
+ if (!data.isArray()) { cb(true, data, {}); return; }
+ QJsonArray arr = data.toArray();
+
+ if (op == "reverse") {
+ QJsonArray out;
+ for (int i = arr.size() - 1; i >= 0; --i) out.append(arr[i]);
+ cb(true, out, {});
+ } else if (op == "unique") {
+ QSet<QString> seen;
+ QJsonArray out;
+ for (const QJsonValue& v : arr) {
+ QString key = v.isObject()
+ ? QString::fromUtf8(QJsonDocument(v.toObject()).toJson(QJsonDocument::Compact))
+ : v.toVariant().toString();
+ if (!seen.contains(key)) { seen.insert(key); out.append(v); }
+ }
+ cb(true, out, {});
+ } else if (op == "flatten") {
+ QJsonArray out;
+ for (const QJsonValue& v : arr) {
+ if (v.isArray()) { for (const QJsonValue& inner : v.toArray()) out.append(inner); }
+ else out.append(v);
+ }
+ cb(true, out, {});
+ } else if (op == "shuffle") {
+ QVector<QJsonValue> vec;
+ vec.reserve(arr.size());
+ for (const QJsonValue& v : arr) vec.append(v);
+ for (int i = vec.size() - 1; i > 0; --i) {
+ int j = static_cast<int>(QRandomGenerator::global()->bounded(i + 1));
+ std::swap(vec[i], vec[j]);
+ }
+ QJsonArray out;
+ for (const QJsonValue& v : vec) out.append(v);
+ cb(true, out, {});
+ } else if (op == "concatenate") {
+ // Merge all sub-arrays in inputs into one
+ QJsonArray out = arr;
+ for (int i = 1; i < inputs.size(); ++i)
+ if (inputs[i].isArray())
+ for (const QJsonValue& v : inputs[i].toArray()) out.append(v);
+ cb(true, out, {});
+ } else {
+ cb(true, arr, {});
+ }
},
});
@@ -306,7 +564,42 @@ void register_utility_nodes(NodeRegistry& registry) {
""},
{"key", "Key", "string", "", {}, "Key for HMAC operations"},
},
- .execute = nullptr,
+ .execute =
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ QString op = params.value("operation").toString("sha256");
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+
+ // Get text to operate on
+ QString text = data.isString() ? data.toString()
+ : data.isObject() ? QString::fromUtf8(
+ QJsonDocument(data.toObject()).toJson(QJsonDocument::Compact))
+ : QString::number(data.toDouble());
+
+ if (op == "base64_encode") {
+ QString encoded = QString::fromLatin1(text.toUtf8().toBase64());
+ cb(true, QJsonObject{{"result", encoded}, {"operation", op}}, {});
+ } else if (op == "base64_decode") {
+ QString decoded = QString::fromUtf8(QByteArray::fromBase64(text.toLatin1()));
+ cb(true, QJsonObject{{"result", decoded}, {"operation", op}}, {});
+ } else if (op == "md5") {
+ QString hash = QString::fromLatin1(
+ QCryptographicHash::hash(text.toUtf8(), QCryptographicHash::Md5).toHex());
+ cb(true, QJsonObject{{"result", hash}, {"operation", op}}, {});
+ } else if (op == "hmac_sha256") {
+ // Qt doesn't have built-in HMAC — return sha256 of key+text as fallback
+ QString key = params.value("key").toString();
+ QString combined = key + text;
+ QString hash = QString::fromLatin1(
+ QCryptographicHash::hash(combined.toUtf8(), QCryptographicHash::Sha256).toHex());
+ cb(true, QJsonObject{{"result", hash}, {"operation", op}, {"note", "simplified_hmac"}}, {});
+ } else {
+ // sha256 default
+ QString hash = QString::fromLatin1(
+ QCryptographicHash::hash(text.toUtf8(), QCryptographicHash::Sha256).toHex());
+ cb(true, QJsonObject{{"result", hash}, {"operation", op}}, {});
+ }
+ },
});
// ── Database ──────────────────────────────────────────────────
@@ -422,9 +715,27 @@ void register_utility_nodes(NodeRegistry& registry) {
{"agg", "Aggregation", "select", "sum", {"sum", "mean", "count", "first", "last"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ QString op = params.value("operation").toString("flatten");
+ QString key = params.value("key").toString();
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+
+ if (op == "flatten" && data.isArray()) {
+ QJsonArray out;
+ for (const QJsonValue& v : data.toArray()) {
+ if (v.isArray()) for (const QJsonValue& inner : v.toArray()) out.append(inner);
+ else out.append(v);
+ }
+ cb(true, out, {}); return;
+ }
+ if (op == "nest" && data.isArray()) {
+ // Wrap each item under "key" if provided, else wrap all items under "items"
+ QJsonObject out;
+ out[key.isEmpty() ? "items" : key] = data.toArray();
+ cb(true, out, {}); return;
+ }
+ cb(true, data, {});
},
});
@@ -444,9 +755,52 @@ void register_utility_nodes(NodeRegistry& registry) {
{"field", "Field", "string", "", {}, "Field to normalize"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ QString method = params.value("method").toString("min_max");
+ QString field = params.value("field").toString();
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ if (!data.isArray()) { cb(true, data, {}); return; }
+
+ QJsonArray arr = data.toArray();
+ // Extract numeric values
+ QVector<double> vals;
+ vals.reserve(arr.size());
+ for (const QJsonValue& v : arr)
+ vals.append(v.isObject() ? v.toObject().value(field).toDouble() : v.toDouble());
+
+ if (vals.isEmpty()) { cb(true, data, {}); return; }
+
+ double min_v = *std::min_element(vals.begin(), vals.end());
+ double max_v = *std::max_element(vals.begin(), vals.end());
+ double mean_v = 0;
+ for (double d : vals) mean_v += d;
+ mean_v /= vals.size();
+ double std_v = 0;
+ for (double d : vals) std_v += (d - mean_v) * (d - mean_v);
+ std_v = std::sqrt(std_v / vals.size());
+
+ QJsonArray out;
+ for (int i = 0; i < arr.size(); ++i) {
+ double norm = 0;
+ if (method == "min_max")
+ norm = (max_v - min_v) > 0 ? (vals[i] - min_v) / (max_v - min_v) : 0;
+ else if (method == "z_score")
+ norm = std_v > 0 ? (vals[i] - mean_v) / std_v : 0;
+ else if (method == "log")
+ norm = vals[i] > 0 ? std::log(vals[i]) : 0;
+ else // robust: (x - median) / IQR — approximate with mean/std
+ norm = std_v > 0 ? (vals[i] - mean_v) / std_v : 0;
+
+ if (arr[i].isObject()) {
+ QJsonObject obj = arr[i].toObject();
+ obj[field + "_norm"] = norm;
+ out.append(obj);
+ } else {
+ out.append(norm);
+ }
+ }
+ cb(true, out, {});
},
});
@@ -467,9 +821,50 @@ void register_utility_nodes(NodeRegistry& registry) {
{"field", "Field", "string", "close", {}, "Field to compute on"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ int window = static_cast<int>(params.value("window").toDouble(20));
+ QString op = params.value("operation").toString("mean");
+ QString field = params.value("field").toString("close");
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ if (!data.isArray() || window < 1) { cb(true, data, {}); return; }
+
+ QJsonArray arr = data.toArray();
+ QVector<double> vals;
+ vals.reserve(arr.size());
+ for (const QJsonValue& v : arr)
+ vals.append(v.isObject() ? v.toObject().value(field).toDouble() : v.toDouble());
+
+ QJsonArray out;
+ for (int i = 0; i < arr.size(); ++i) {
+ int start = qMax(0, i - window + 1);
+ QVector<double> w = vals.mid(start, i - start + 1);
+ double result = 0;
+ if (op == "sum") {
+ for (double d : w) result += d;
+ } else if (op == "min") {
+ result = *std::min_element(w.begin(), w.end());
+ } else if (op == "max") {
+ result = *std::max_element(w.begin(), w.end());
+ } else if (op == "std") {
+ double m = 0; for (double d : w) m += d; m /= w.size();
+ for (double d : w) result += (d - m) * (d - m);
+ result = std::sqrt(result / w.size());
+ } else if (op == "median") {
+ QVector<double> s = w; std::sort(s.begin(), s.end());
+ result = s[s.size() / 2];
+ } else { // mean
+ for (double d : w) result += d; result /= w.size();
+ }
+ if (arr[i].isObject()) {
+ QJsonObject obj = arr[i].toObject();
+ obj[field + "_" + op + "_" + QString::number(window)] = result;
+ out.append(obj);
+ } else {
+ out.append(result);
+ }
+ }
+ cb(true, out, {});
},
});
@@ -490,9 +885,38 @@ void register_utility_nodes(NodeRegistry& registry) {
{"fill", "Fill Value", "select", "null", {"null", "zero", "forward_fill", "backward_fill"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ int periods = static_cast<int>(params.value("periods").toDouble(1));
+ QString field = params.value("field").toString();
+ QString fill = params.value("fill").toString("null");
+ QJsonValue data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ if (!data.isArray()) { cb(true, data, {}); return; }
+
+ QJsonArray arr = data.toArray();
+ QJsonArray out;
+ int n = arr.size();
+ for (int i = 0; i < n; ++i) {
+ int src = i - periods;
+ QJsonValue lagged;
+ if (src >= 0 && src < n) {
+ lagged = field.isEmpty() ? arr[src]
+ : QJsonValue(arr[src].toObject().value(field));
+ } else {
+ if (fill == "zero") lagged = 0.0;
+ else if (fill == "forward_fill" && i > 0) lagged = field.isEmpty() ? arr[i-1] : QJsonValue(arr[i-1].toObject().value(field));
+ else if (fill == "backward_fill" && src+n >= 0) lagged = field.isEmpty() ? arr[qMax(0,src+n)] : QJsonValue(arr[qMax(0,src+n)].toObject().value(field));
+ else lagged = QJsonValue::Null;
+ }
+ if (field.isEmpty()) {
+ out.append(lagged);
+ } else {
+ QJsonObject obj = arr[i].isObject() ? arr[i].toObject() : QJsonObject{};
+ obj[field + "_lag_" + QString::number(periods)] = lagged;
+ out.append(obj);
+ }
+ }
+ cb(true, out, {});
},
});
@@ -541,9 +965,26 @@ void register_utility_nodes(NodeRegistry& registry) {
{"cache_key", "Cache Key", "string", "", {}, "Custom key (auto-generated if empty)"},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- cb(true, inputs.isEmpty() ? QJsonValue{} : inputs[0], {});
+ static QHash<QString, QPair<QJsonValue, qint64>> cache;
+ auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ int ttl = static_cast<int>(params.value("ttl_seconds").toDouble(300)) * 1000;
+ QString key = params.value("cache_key").toString();
+ if (key.isEmpty()) {
+ // Auto-key from data fingerprint
+ key = data.isObject()
+ ? QString::fromUtf8(QJsonDocument(data.toObject()).toJson(QJsonDocument::Compact)).left(64)
+ : data.toVariant().toString().left(64);
+ }
+ qint64 now = QDateTime::currentMSecsSinceEpoch();
+ auto it = cache.find(key);
+ if (it != cache.end() && (now - it.value().second) < ttl) {
+ cb(true, it.value().first, {});
+ return;
+ }
+ cache.insert(key, {data, now});
+ cb(true, data, {});
},
});
@@ -614,9 +1055,39 @@ void register_utility_nodes(NodeRegistry& registry) {
.execute =
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- // Placeholder: always passes
auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ QString condition = params.value("condition").toString();
+ QString message = params.value("message").toString("Assertion failed");
+
+ // Evaluate simple expressions: field op value
+ // Supports: {{field}} > value, {{field}} == value, {{field}} != value
+ bool passed = true;
+ if (!condition.isEmpty() && data.isObject()) {
+ QJsonObject obj = data.toObject();
+ static const QRegularExpression expr_re(
+ R"(\{\{(\w+)\}\}\s*(==|!=|>|<|>=|<=|contains)\s*(.+))");
+ QRegularExpressionMatch m = expr_re.match(condition.trimmed());
+ if (m.hasMatch()) {
+ QString field = m.captured(1);
+ QString op = m.captured(2).trimmed();
+ QString rhs = m.captured(3).trimmed();
+ QJsonValue lhsv = obj.value(field);
+ double lhsd = lhsv.toDouble();
+ double rhsd = rhs.toDouble();
+ QString lhss = lhsv.isString() ? lhsv.toString() : QString::number(lhsd);
+ if (op == "==") passed = (lhss == rhs);
+ else if (op == "!=") passed = (lhss != rhs);
+ else if (op == ">") passed = (lhsd > rhsd);
+ else if (op == "<") passed = (lhsd < rhsd);
+ else if (op == ">=") passed = (lhsd >= rhsd);
+ else if (op == "<=") passed = (lhsd <= rhsd);
+ else if (op == "contains") passed = lhss.contains(rhs);
+ }
+ }
+ if (!passed)
+ cb(false, {}, message);
+ else
+ cb(true, data, {});
},
});
@@ -638,11 +1109,30 @@ void register_utility_nodes(NodeRegistry& registry) {
.execute =
[](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
+ QString tmpl = params.value("template").toString();
+ QJsonObject input_obj = inputs.isEmpty() ? QJsonObject{} : inputs[0].toObject();
+
+ // Replace all {{field}} occurrences with the corresponding input field.
+ static const QRegularExpression placeholder_re(R"(\{\{(\w+)\}\})");
+ QString rendered = tmpl;
+ QRegularExpressionMatchIterator it = placeholder_re.globalMatch(tmpl);
+ // Collect replacements first to avoid offset issues.
+ QVector<std::pair<QString, QString>> replacements;
+ while (it.hasNext()) {
+ QRegularExpressionMatch m = it.next();
+ QString full_match = m.captured(0); // e.g. "{{name}}"
+ QString key = m.captured(1); // e.g. "name"
+ QJsonValue val = input_obj.value(key);
+ QString replacement = val.isString()
+ ? val.toString()
+ : QString::number(val.toDouble());
+ replacements.append({full_match, replacement});
+ }
+ for (const auto& [placeholder, value] : replacements)
+ rendered.replace(placeholder, value);
+
QJsonObject out;
- out["template"] = params.value("template").toString();
- out["rendered"] = params.value("template").toString(); // placeholder
- if (!inputs.isEmpty())
- out["input"] = inputs[0];
+ out["rendered"] = rendered;
cb(true, out, {});
},
});