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.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
// src/services/agents/AgentService_Execution.cpp
//
// Hot path for running a single agent / team / multi-agent flow:
// run_agent, run_agent_streaming, route_query (intent routing), run_team,
// run_agent_structured, execute_routed_query, execute_multi_query.
//
// Part of the partial-class split of AgentService.cpp.
#include "auth/AuthManager.h"
#include "core/logging/Logger.h"
#include "datahub/DataHub.h"
#include "datahub/TopicPolicy.h"
#include "mcp/McpProvider.h"
#include "mcp/McpTypes.h"
#include "mcp/TerminalMcpBridge.h"
#include "python/PythonRunner.h"
#include "services/agents/AgentService.h"
#include "services/llm/LlmService.h"
#include "storage/cache/CacheManager.h"
#include "storage/repositories/LlmConfigRepository.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QElapsedTimer>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMetaObject>
#include <QPointer>
#include <QProcess>
#include <QTimer>
#include <QUuid>
#include <QVariant>
#include <algorithm>
#include <memory>
namespace fincept::services {
QString AgentService::run_agent(const QString& query, const QJsonObject& config) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
LOG_INFO("AgentService", QString("Running agent query [%1]: %2").arg(req_id.left(8), query.left(80)));
QJsonObject params;
params["query"] = query;
QPointer<AgentService> self = this;
run_python_stdin("run", params, config, [self, req_id](bool ok, QJsonObject result) {
if (!self)
return;
AgentExecutionResult r;
r.request_id = req_id;
r.success = ok && result["success"].toBool(ok);
r.execution_time_ms = result["execution_time_ms"].toInt();
if (r.success) {
if (result.contains("response"))
r.response = result["response"].toString();
else if (result.contains("result"))
r.response = result["result"].toString();
else if (result.contains("data"))
r.response = QJsonDocument(result["data"].toObject()).toJson(QJsonDocument::Indented);
else
r.response = QJsonDocument(result).toJson(QJsonDocument::Indented);
} else {
r.error = result["error"].toString("Agent execution failed");
}
emit self->agent_result(r);
self->publish_agent_result(r, /*final=*/true);
});
return req_id;
}
// ── Streaming agent execution ─────────────────────────────────────────────────
QString AgentService::run_agent_streaming(const QString& query, const QJsonObject& config) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
LOG_INFO("AgentService", QString("Streaming agent query [%1]: %2").arg(req_id.left(8), query.left(80)));
auto& py = python::PythonRunner::instance();
if (!py.is_available()) {
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = "Python not available";
// Deferred: the caller stores the returned request id after this returns,
// so a synchronous emit would be dropped by its request-id guard.
QPointer<AgentService> unavailable_self = this;
QMetaObject::invokeMethod(
this,
[unavailable_self, r]() {
if (!unavailable_self)
return;
emit unavailable_self->agent_stream_done(r);
unavailable_self->publish_agent_result(r, /*final=*/true);
},
Qt::QueuedConnection);
return req_id;
}
QJsonObject params;
params["query"] = query;
QJsonObject payload = build_payload("run", params, config);
QByteArray payload_bytes = QJsonDocument(payload).toJson(QJsonDocument::Compact);
// Run-scoped bridge token minted by build_payload — retired when the process
// exits (the non-streaming path already does this in run_python_stdin).
const QString run_token =
payload.value("config").toObject().value("terminal_mcp_token").toString();
QString python_path = py.python_path();
QString script_path = py.scripts_dir() + "/agents/finagent_core/main.py";
auto* proc = new QProcess(this);
// Share the standard Python env + cwd + Windows console suppression with
// PythonRunner so every finagent spawn sees the same FINCEPT_DATA_DIR,
// FINAGENT_DATA_DIR, PYTHONPATH and FINCEPT_AGENT_DATA_DIR.
proc->setProcessEnvironment(agent_process_env());
proc->setWorkingDirectory(py.scripts_dir());
#ifdef _WIN32
proc->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {
cpa->flags |= 0x08000000; // CREATE_NO_WINDOW
});
#endif
QPointer<AgentService> self = this;
auto timer = std::make_shared<QElapsedTimer>();
auto accumulated = std::make_shared<QString>();
auto final_json_line = std::make_shared<QString>();
auto done_emitted = std::make_shared<bool>(false);
timer->start();
active_runs_.insert(req_id, ActiveRun{proc, done_emitted});
// Started from Agent Studio → notify on finish if the user has moved on.
if (visible_agent_screens_ > 0)
notify_runs_.insert(req_id);
// Read stdout line by line as process writes
connect(proc, &QProcess::readyReadStandardOutput, this,
[self, proc, accumulated, final_json_line, done_emitted, req_id]() {
if (!self)
return;
while (proc->canReadLine()) {
QString line = QString::fromUtf8(proc->readLine()).trimmed();
if (line.isEmpty())
continue;
// Python emits "TOKEN: {content}" (stream_print adds a space after colon)
auto extract = [](const QString& s, const QString& prefix) -> QString {
QString rest = s.mid(prefix.length());
// Strip one leading space if present
if (rest.startsWith(' '))
rest = rest.mid(1);
// Unescape \n -> newline
rest.replace("\\n", "\n").replace("\\\\", "\\");
return rest;
};
if (line.startsWith('{')) {
// Final JSON result line — capture it for the finished handler
*final_json_line = line;
} else if (line.startsWith("TOKEN:")) {
QString token = extract(line, "TOKEN:");
*accumulated += token;
emit self->agent_stream_token(req_id, token);
self->publish_agent_token(req_id, token);
} else if (line.startsWith("THINKING:")) {
QString status = extract(line, "THINKING:");
emit self->agent_stream_thinking(req_id, status);
self->publish_agent_status(req_id, status);
} else if (line.startsWith("TOOL:")) {
QString status = "Tool: " + extract(line, "TOOL:");
emit self->agent_stream_thinking(req_id, status);
self->publish_agent_status(req_id, status);
} else if (line.startsWith("TOOL_RESULT:")) {
QString status = "Result: " + extract(line, "TOOL_RESULT:");
emit self->agent_stream_thinking(req_id, status);
self->publish_agent_status(req_id, status);
} else if (line.startsWith("DONE:")) {
// DONE carries the full cleaned response — use it if accumulated is empty
QString done_content = extract(line, "DONE:");
if (accumulated->trimmed().isEmpty() && !done_content.isEmpty())
*accumulated = done_content;
} else if (line.startsWith("ERROR:")) {
if (!*done_emitted) {
*done_emitted = true;
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = extract(line, "ERROR:");
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
}
}
}
});
connect(
proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
[self, proc, accumulated, final_json_line, done_emitted, timer, req_id, run_token](int exit_code,
QProcess::ExitStatus) {
mcp::TerminalMcpBridge::instance().end_run(run_token);
int elapsed = timer->elapsed();
// Drain any remaining stdout
QString remaining = QString::fromUtf8(proc->readAllStandardOutput());
QString stderr_str = QString::fromUtf8(proc->readAllStandardError());
proc->deleteLater();
if (!self)
return;
self->active_runs_.remove(req_id);
if (*done_emitted)
return;
*done_emitted = true;
// Scan remaining stdout for final JSON line (may not have been read yet)
for (const QString& line : remaining.split('\n')) {
QString t = line.trimmed();
if (t.startsWith('{'))
*final_json_line = t;
}
AgentExecutionResult r;
r.request_id = req_id;
r.execution_time_ms = elapsed;
QJsonDocument doc = QJsonDocument::fromJson(final_json_line->toUtf8());
if (!doc.isNull() && doc.object()["success"].toBool()) {
QString json_response = doc.object()["response"].toString();
r.success = true;
r.response = json_response.isEmpty() ? accumulated->trimmed() : json_response;
} else if (!accumulated->trimmed().isEmpty()) {
r.success = true;
r.response = accumulated->trimmed();
} else {
r.success = false;
r.error = exit_code != 0 ? stderr_str.left(500) : "No response received";
}
LOG_INFO("AgentService", QString("Streaming completed in %1ms").arg(elapsed));
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
});
connect(proc, &QProcess::errorOccurred, this,
[self, proc, done_emitted, req_id, run_token](QProcess::ProcessError e) {
// Only a failed spawn has no finished() signal; a crash is reported
// by the finished handler with the child's stderr attached.
if (e != QProcess::FailedToStart)
return;
mcp::TerminalMcpBridge::instance().end_run(run_token);
QString err = proc->errorString();
proc->deleteLater();
if (!self)
return;
self->active_runs_.remove(req_id);
if (*done_emitted)
return;
*done_emitted = true;
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = "Process error: " + err;
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
});
LOG_INFO("AgentService", QString("Starting streaming agent (%1 bytes payload)").arg(payload_bytes.size()));
proc->start(python_path, {script_path, "--stdin", "--stream"});
proc->write(payload_bytes);
proc->closeWriteChannel();
return req_id;
}
// ── Cancellation ─────────────────────────────────────────────────────────────
bool AgentService::cancel_run(const QString& request_id) {
const auto it = active_runs_.constFind(request_id);
if (it == active_runs_.cend())
return false; // finished already, or not a streaming run
const ActiveRun run = it.value();
active_runs_.remove(request_id);
auto* proc = qobject_cast<QProcess*>(run.proc.data());
if (!proc || !run.done || *run.done)
return false;
// Claim the result first: the process-exit handlers see done == true and stay
// silent, so the UI gets exactly one terminal event for this request.
*run.done = true;
LOG_INFO("AgentService", QString("Cancelling run [%1]").arg(request_id.left(8)));
// kill(), not terminate(): the child is a console-less python.exe, which
// ignores WM_CLOSE on Windows. The finished() handler still runs and retires
// the bridge token / schedules the QProcess for deletion.
proc->kill();
AgentExecutionResult r;
r.request_id = request_id;
r.success = false;
r.error = QString::fromLatin1(kCancelledError);
emit agent_stream_done(r);
publish_agent_result(r, /*final=*/true);
return true;
}
// ── Query routing ────────────────────────────────────────────────────────────
QString AgentService::route_query(const QString& query) {
LOG_INFO("AgentService", QString("Routing query: %1").arg(query.left(80)));
QJsonObject params;
params["query"] = query;
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QPointer<AgentService> self = this;
run_python_stdin("route_query", params, {}, [self, req_id](bool ok, QJsonObject result) {
if (!self)
return;
RoutingResult r;
r.request_id = req_id;
r.success = ok && result["success"].toBool(ok);
r.agent_id = result["agent_id"].toString();
r.intent = result["intent"].toString();
r.confidence = result["confidence"].toDouble();
r.config = result["config"].toObject();
QJsonArray kw = result["matched_keywords"].toArray();
for (const auto& k : kw)
r.matched_keywords.append(k.toString());
emit self->routing_result(r);
self->publish_routing_result(r);
});
return req_id;
}
// ── Team execution ───────────────────────────────────────────────────────────
QString AgentService::run_team(const QString& query, const QJsonObject& team_config) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
LOG_INFO("AgentService", QString("Running team query [%1]: %2").arg(req_id.left(8), query.left(80)));
auto& py = python::PythonRunner::instance();
if (!py.is_available()) {
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = "Python not available";
// Deferred: the caller stores the returned request id after this returns,
// so a synchronous emit would be dropped by its request-id guard.
QPointer<AgentService> unavailable_self = this;
QMetaObject::invokeMethod(
this,
[unavailable_self, r]() {
if (!unavailable_self)
return;
emit unavailable_self->agent_stream_done(r);
unavailable_self->publish_agent_result(r, /*final=*/true);
},
Qt::QueuedConnection);
return req_id;
}
QJsonObject params;
params["query"] = query;
params["team_config"] = team_config;
// Promote coordinator model to active_llm so Python resolves it correctly
QJsonObject coord_config;
if (team_config.contains("model"))
coord_config["model"] = team_config["model"];
QJsonObject payload = build_payload("run_team", params, coord_config);
QByteArray payload_bytes = QJsonDocument(payload).toJson(QJsonDocument::Compact);
// Run-scoped bridge token minted by build_payload — retired on process exit.
const QString run_token =
payload.value("config").toObject().value("terminal_mcp_token").toString();
QString python_path = py.python_path();
QString script_path = py.scripts_dir() + "/agents/finagent_core/main.py";
auto* proc = new QProcess(this);
// Share the standard Python env + cwd + Windows console suppression with
// PythonRunner so every finagent spawn sees the same FINCEPT_DATA_DIR,
// FINAGENT_DATA_DIR, PYTHONPATH and FINCEPT_AGENT_DATA_DIR.
proc->setProcessEnvironment(agent_process_env());
proc->setWorkingDirectory(py.scripts_dir());
#ifdef _WIN32
proc->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {
cpa->flags |= 0x08000000; // CREATE_NO_WINDOW
});
#endif
QPointer<AgentService> self = this;
auto timer = std::make_shared<QElapsedTimer>();
auto accumulated = std::make_shared<QString>();
auto final_json = std::make_shared<QString>();
auto done_emitted = std::make_shared<bool>(false);
timer->start();
active_runs_.insert(req_id, ActiveRun{proc, done_emitted});
// Started from Agent Studio → notify on finish if the user has moved on.
if (visible_agent_screens_ > 0)
notify_runs_.insert(req_id);
connect(proc, &QProcess::readyReadStandardOutput, this,
[self, proc, accumulated, final_json, done_emitted, req_id]() {
if (!self)
return;
while (proc->canReadLine()) {
QString line = QString::fromUtf8(proc->readLine()).trimmed();
if (line.isEmpty())
continue;
auto extract = [](const QString& s, const QString& prefix) -> QString {
QString rest = s.mid(prefix.length());
if (rest.startsWith(' '))
rest = rest.mid(1);
rest.replace("\\n", "\n").replace("\\\\", "\\");
return rest;
};
if (line.startsWith('{')) {
*final_json = line;
} else if (line.startsWith("TOKEN:")) {
QString token = extract(line, "TOKEN:");
*accumulated += token;
emit self->agent_stream_token(req_id, token);
self->publish_agent_token(req_id, token);
} else if (line.startsWith("THINKING:")) {
QString status = extract(line, "THINKING:");
emit self->agent_stream_thinking(req_id, status);
self->publish_agent_status(req_id, status);
} else if (line.startsWith("TOOL:")) {
QString status = "Tool: " + extract(line, "TOOL:");
emit self->agent_stream_thinking(req_id, status);
self->publish_agent_status(req_id, status);
} else if (line.startsWith("DONE:")) {
QString done_content = extract(line, "DONE:");
if (accumulated->trimmed().isEmpty() && !done_content.isEmpty())
*accumulated = done_content;
} else if (line.startsWith("ERROR:")) {
if (!*done_emitted) {
*done_emitted = true;
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = extract(line, "ERROR:");
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
}
}
}
});
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
[self, proc, accumulated, final_json, done_emitted, timer, req_id, run_token](int exit_code,
QProcess::ExitStatus) {
mcp::TerminalMcpBridge::instance().end_run(run_token);
int elapsed = timer->elapsed();
QString remaining = QString::fromUtf8(proc->readAllStandardOutput());
QString stderr_str = QString::fromUtf8(proc->readAllStandardError());
proc->deleteLater();
if (!self)
return;
self->active_runs_.remove(req_id);
if (*done_emitted)
return;
*done_emitted = true;
for (const QString& line : remaining.split('\n')) {
QString t = line.trimmed();
if (t.startsWith('{'))
*final_json = t;
}
AgentExecutionResult r;
r.request_id = req_id;
r.execution_time_ms = elapsed;
QJsonDocument doc = QJsonDocument::fromJson(final_json->toUtf8());
if (!doc.isNull() && doc.object()["success"].toBool()) {
QString json_response = doc.object()["response"].toString();
r.success = true;
r.response = json_response.isEmpty() ? accumulated->trimmed() : json_response;
} else if (!accumulated->trimmed().isEmpty()) {
r.success = true;
r.response = accumulated->trimmed();
} else {
r.success = false;
r.error = exit_code != 0 ? stderr_str.left(500) : "No response from team";
}
LOG_INFO("AgentService", QString("Team completed in %1ms").arg(elapsed));
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
});
connect(proc, &QProcess::errorOccurred, this, [self, proc, done_emitted, req_id, run_token](QProcess::ProcessError e) {
// Only a failed spawn has no finished() signal (see run_agent_streaming).
if (e != QProcess::FailedToStart)
return;
mcp::TerminalMcpBridge::instance().end_run(run_token);
QString err = proc->errorString();
proc->deleteLater();
if (!self)
return;
self->active_runs_.remove(req_id);
if (*done_emitted)
return;
*done_emitted = true;
AgentExecutionResult r;
r.request_id = req_id;
r.success = false;
r.error = "Process error: " + err;
emit self->agent_stream_done(r);
self->publish_agent_result(r, /*final=*/true);
});
LOG_INFO("AgentService", QString("Starting team stream (%1 bytes payload, %2 members)")
.arg(payload_bytes.size())
.arg(team_config["members"].toArray().size()));
proc->start(python_path, {script_path, "--stdin", "--stream"});
proc->write(payload_bytes);
proc->closeWriteChannel();
return req_id;
}
// ── Workflow execution ───────────────────────────────────────────────────────
QString AgentService::run_agent_structured(const QString& query, const QJsonObject& config,
const QString& output_model) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
LOG_INFO("AgentService",
QString("Running structured agent [%1] (%2): %3").arg(req_id.left(8), output_model, query.left(60)));
QJsonObject params;
params["query"] = query;
params["output_model"] = output_model;
QPointer<AgentService> self = this;
run_python_stdin("run_structured", params, config, [self, req_id](bool ok, QJsonObject result) {
if (!self)
return;
AgentExecutionResult r;
r.request_id = req_id;
r.success = ok && result["success"].toBool(ok);
r.execution_time_ms = result["execution_time_ms"].toInt();
r.response = result.contains("response") ? result["response"].toString()
: QJsonDocument(result).toJson(QJsonDocument::Indented);
r.error = result["error"].toString();
emit self->agent_result(r);
self->publish_agent_result(r, /*final=*/true);
});
return req_id;
}
// ── Routed query execution ───────────────────────────────────────────────────
void AgentService::execute_routed_query(const QString& query, const QJsonObject& config, const QString& session_id) {
LOG_INFO("AgentService", QString("Execute routed query: %1").arg(query.left(60)));
QJsonObject params;
params["query"] = query;
if (!session_id.isEmpty())
params["session_id"] = session_id;
QPointer<AgentService> self = this;
run_python_stdin("execute_query", params, config, [self](bool ok, QJsonObject result) {
if (!self)
return;
AgentExecutionResult r;
r.success = ok && result["success"].toBool(ok);
r.execution_time_ms = result["execution_time_ms"].toInt();
r.response = result.contains("response") ? result["response"].toString()
: QJsonDocument(result).toJson(QJsonDocument::Indented);
r.error = result["error"].toString();
emit self->agent_result(r);
self->publish_agent_result(r, /*final=*/true);
});
}
// ── Multi-query ──────────────────────────────────────────────────────────────
void AgentService::execute_multi_query(const QString& query, bool aggregate, const QJsonObject& config) {
LOG_INFO("AgentService", QString("Multi-query: %1").arg(query.left(60)));
QJsonObject params;
params["query"] = query;
params["aggregate"] = aggregate;
QPointer<AgentService> self = this;
run_python_stdin("execute_multi_query", params, config, [self](bool ok, QJsonObject result) {
if (!self)
return;
if (ok)
emit self->multi_query_result(result);
else
emit self->error_occurred("multi_query", result["error"].toString());
});
}
// ── Financial workflows (specialized) ────────────────────────────────────────
// ── Agentic Mode ─────────────────────────────────────────────────────────────
// Spawns a streaming Python subprocess that runs an AgenticRunner. Events
// arrive as AGENTIC_EVENT: <json> lines on stdout; each is forwarded to the
// `task_event` signal and DataHub topic `task:event:<task_id>`.
QString AgentService::run_agentic_streaming(const QString& action, const QJsonObject& params, const QJsonObject& config,
const QString& known_task_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
LOG_INFO("AgentService",
QString("Agentic streaming [%1] action=%2 task=%3").arg(req_id.left(8), action, known_task_id.left(8)));
auto& py = python::PythonRunner::instance();
if (!py.is_available()) {
QJsonObject evt{{"kind", "error"}, {"task_id", known_task_id}, {"error", "Python not available"}};
publish_task_event(known_task_id, evt);
return req_id;
}
QJsonObject payload = build_payload(action, params, config);
QByteArray payload_bytes = QJsonDocument(payload).toJson(QJsonDocument::Compact);
// Run-scoped bridge token minted by build_payload — retired on process exit.
const QString run_token =
payload.value("config").toObject().value("terminal_mcp_token").toString();
QString python_path = py.python_path();
QString script_path = py.scripts_dir() + "/agents/finagent_core/main.py";
auto* proc = new QProcess(this);
proc->setProcessEnvironment(agent_process_env());
proc->setWorkingDirectory(py.scripts_dir());
#ifdef _WIN32
proc->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* cpa) {
cpa->flags |= 0x08000000; // CREATE_NO_WINDOW
});
#endif
QPointer<AgentService> self = this;
auto resolved_task_id = std::make_shared<QString>(known_task_id);
auto done_emitted = std::make_shared<bool>(false);
// Streaming line reader: parse only AGENTIC_EVENT: <json>; ignore other
// lines (the Python wrapper still emits "thinking ..." / "done" via
// stream_print which we don't need to surface here).
connect(proc, &QProcess::readyReadStandardOutput, this, [self, proc, resolved_task_id, done_emitted, req_id]() {
if (!self)
return;
static const QString kPrefix = QStringLiteral("AGENTIC_EVENT:");
while (proc->canReadLine()) {
QString line = QString::fromUtf8(proc->readLine()).trimmed();
if (!line.startsWith(kPrefix))
continue;
QString rest = line.mid(kPrefix.length()).trimmed();
QJsonDocument doc = QJsonDocument::fromJson(rest.toUtf8());
if (!doc.isObject())
continue;
QJsonObject evt = doc.object();
// Adopt the task_id from the first event that carries one
// (start_task scenario; resume_task already has it).
QString tid = evt.value(QStringLiteral("task_id")).toString();
if (tid.isEmpty())
tid = *resolved_task_id;
else
*resolved_task_id = tid;
// Tag with the C++ correlator so UI panels can match.
evt["request_id"] = req_id;
self->publish_task_event(tid, evt);
const QString kind = evt.value(QStringLiteral("kind")).toString();
if (kind == QLatin1String("done") || kind == QLatin1String("error") || kind == QLatin1String("cancelled")) {
*done_emitted = true;
}
}
});
connect(proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
[self, proc, resolved_task_id, done_emitted, req_id, run_token](int exit_code, QProcess::ExitStatus) {
mcp::TerminalMcpBridge::instance().end_run(run_token);
QString stderr_str = QString::fromUtf8(proc->readAllStandardError());
// Drain any remaining stdout in case the last events arrived
// in the same chunk as exit.
QString remaining = QString::fromUtf8(proc->readAllStandardOutput());
static const QString kPrefix = QStringLiteral("AGENTIC_EVENT:");
for (const QString& raw : remaining.split('\n')) {
QString line = raw.trimmed();
if (!line.startsWith(kPrefix))
continue;
QString rest = line.mid(kPrefix.length()).trimmed();
QJsonDocument doc = QJsonDocument::fromJson(rest.toUtf8());
if (!doc.isObject())
continue;
QJsonObject evt = doc.object();
QString tid = evt.value(QStringLiteral("task_id")).toString();
if (tid.isEmpty())
tid = *resolved_task_id;
else
*resolved_task_id = tid;
evt["request_id"] = req_id;
if (self)
self->publish_task_event(tid, evt);
const QString kind = evt.value(QStringLiteral("kind")).toString();
if (kind == QLatin1String("done") || kind == QLatin1String("error") ||
kind == QLatin1String("cancelled")) {
*done_emitted = true;
}
}
proc->deleteLater();
if (!self)
return;
// If the subprocess died without emitting a terminal event,
// synthesise an error event so UI can clean up.
if (!*done_emitted) {
QJsonObject evt{{"kind", "error"},
{"task_id", *resolved_task_id},
{"request_id", req_id},
{"error", exit_code != 0
? stderr_str.left(500)
: QStringLiteral("Subprocess exited without terminal event")}};
self->publish_task_event(*resolved_task_id, evt);
}
});
connect(proc, &QProcess::errorOccurred, this,
[self, proc, resolved_task_id, done_emitted, req_id, run_token](QProcess::ProcessError e) {
// Only a failed spawn has no finished() signal; a crash is
// reported by the finished handler (with stderr).
if (e != QProcess::FailedToStart)
return;
mcp::TerminalMcpBridge::instance().end_run(run_token);
QString err = proc->errorString();
proc->deleteLater();
if (!self || *done_emitted)
return;
*done_emitted = true;
QJsonObject evt{{"kind", "error"},
{"task_id", *resolved_task_id},
{"request_id", req_id},
{"error", QStringLiteral("Process error: ") + err}};
self->publish_task_event(*resolved_task_id, evt);
});
proc->start(python_path, {script_path, "--stdin", "--stream"});
proc->write(payload_bytes);
proc->closeWriteChannel();
return req_id;
}
QString AgentService::start_task(const QString& query, const QJsonObject& config) {
QJsonObject params;
params["query"] = query;
return run_agentic_streaming(QStringLiteral("agentic_start_task"), params, config);
}
namespace {
/// The stored task config minus everything that is minted per run. Python
/// never persists credentials or bridge wiring (AgenticRunner strips them), but
/// `model` IS kept without its key — dropping it here makes build_payload
/// re-resolve a model WITH credentials (agent profile, else the active LLM),
/// exactly as when the task was started.
QJsonObject agent_svc_resume_config(const QJsonObject& task_config) {
QJsonObject cfg = task_config;
cfg.remove(QStringLiteral("model"));
cfg.remove(QStringLiteral("terminal_tools"));
for (const QString& k : cfg.keys()) {
if (k.startsWith(QLatin1String("terminal_mcp_")))
cfg.remove(k);
}
return cfg;
}
} // namespace
QString AgentService::resume_task(const QString& task_id, const QJsonObject& task_config) {
QJsonObject params;
params["task_id"] = task_id;
return run_agentic_streaming(QStringLiteral("agentic_resume_task"), params, agent_svc_resume_config(task_config),
task_id);
}
QString AgentService::reply_to_question(const QString& task_id, const QString& answer, const QJsonObject& task_config) {
QJsonObject params;
params["task_id"] = task_id;
params["answer"] = answer;
return run_agentic_streaming(QStringLiteral("agentic_reply_question"), params, agent_svc_resume_config(task_config),
task_id);
}
// ── Scheduled recurring tasks ────────────────────────────────────────────────
QString AgentService::schedule_create_task(const QString& name, const QString& query, const QString& schedule_expr,
const QJsonObject& config, bool start_now) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["name"] = name;
params["query"] = query;
params["schedule"] = schedule_expr;
params["schedule_config"] = config;
params["start_now"] = start_now;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_schedule_create"), params, {}, [self](bool ok, QJsonObject result) {
if (!self)
return;
if (ok) {
emit self->schedule_created(result.value("schedule_id").toString());
// Python reports the earliest due time across all schedules, so the
// new one (start_now included) arms the timer without a re-list.
self->apply_schedule_due(static_cast<qint64>(result.value("next_run_epoch_ms").toDouble()));
} else {
emit self->error_occurred("schedule_create", result["error"].toString());
}
});
return req_id;
}
QString AgentService::schedule_list() {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_schedule_list"), {}, {}, [self](bool ok, QJsonObject result) {
if (!self)
return;
if (ok) {
const QJsonArray schedules = result.value("schedules").toArray();
// Every listing re-syncs the due-time timer (create / enable /
// disable / delete all end in a list), so it always reflects the DB.
self->apply_schedule_due(static_cast<qint64>(result.value("next_run_epoch_ms").toDouble()));
emit self->schedules_listed(schedules);
} else {
emit self->error_occurred("schedule_list", result["error"].toString());
}
});
return req_id;
}
QString AgentService::delete_task(const QString& task_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["task_id"] = task_id;
// "delete_task" removes the record via the state manager; "agentic_cancel_task"
// only sets a cooperative stop signal and leaves the row behind.
run_python_stdin(QStringLiteral("delete_task"), params, {}, [](bool, QJsonObject) {});
return req_id;
}
QString AgentService::schedule_delete(const QString& schedule_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["schedule_id"] = schedule_id;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_schedule_delete"), params, {}, [self, schedule_id](bool ok, QJsonObject) {
if (!self || !ok)
return;
emit self->schedule_deleted(schedule_id);
self->schedule_list(); // refresh listeners and disarm the tick timer if that was the last one
});
return req_id;
}
QString AgentService::schedule_set_enabled(const QString& schedule_id, bool enabled) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["schedule_id"] = schedule_id;
params["enabled"] = enabled;
QPointer<AgentService> self = this;
// Re-list on success: schedules_listed is the only completion signal the UI
// gets, and listing also re-arms / disarms the tick timer.
run_python_stdin(QStringLiteral("agentic_schedule_set_enabled"), params, {}, [self](bool ok, QJsonObject) {
if (self && ok)
self->schedule_list();
});
return req_id;
}
void AgentService::tick_schedules() {
if (schedule_tick_in_flight_)
return;
schedule_tick_in_flight_ = true;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_schedule_tick"), {}, {}, [self](bool ok, QJsonObject result) {
if (!self)
return;
self->schedule_tick_in_flight_ = false;
if (!ok) {
// Keep the schedule alive: retry on the safety re-check instead of
// dropping it (a transient Python failure must not stop a cadence).
LOG_WARN("AgentService", "Schedule tick failed: " + result.value("error").toString().left(200));
self->next_schedule_due_ms_ = QDateTime::currentMSecsSinceEpoch() + 60 * 1000;
self->rearm_schedule_timer();
return;
}
const QJsonArray due = result.value("due").toArray();
for (const auto& v : due) {
QJsonObject row = v.toObject();
const QString sid = row.value("id").toString();
const QString name = row.value("name").toString();
const QString query = row.value("query").toString();
const QJsonObject cfg = row.value("config").toObject();
// Fire as a normal agentic task — streaming
// events route through task:event:* like manual
// starts. The schedule's id/name is forwarded so
// UI can correlate the task with its trigger.
const QString task_req = self->start_task(query, cfg);
emit self->scheduled_task_fired(sid, name, task_req);
}
self->apply_schedule_due(static_cast<qint64>(result.value("next_run_epoch_ms").toDouble()));
});
}
// Longest single sleep. The timer is re-armed from the cached due time when it
// wakes early, WITHOUT spawning Python, so this only bounds drift from sleep /
// clock changes; it never costs a process.
static constexpr qint64 kScheduleRecheckMs = 15LL * 60 * 1000;
void AgentService::apply_schedule_due(qint64 next_due_ms) {
next_schedule_due_ms_ = next_due_ms > 0 ? next_due_ms : 0;
rearm_schedule_timer();
}
void AgentService::rearm_schedule_timer() {
if (!schedule_timer_) {
schedule_timer_ = new QTimer(this);
schedule_timer_->setSingleShot(true);
QPointer<AgentService> self = this;
connect(schedule_timer_, &QTimer::timeout, this, [self]() {
if (self)
self->on_schedule_timer();
});
}
if (next_schedule_due_ms_ <= 0) {
schedule_timer_->stop();
return;
}
const qint64 delay =
std::clamp<qint64>(next_schedule_due_ms_ - QDateTime::currentMSecsSinceEpoch(), 0, kScheduleRecheckMs);
schedule_timer_->start(static_cast<int>(delay));
}
void AgentService::on_schedule_timer() {
if (next_schedule_due_ms_ <= 0)
return;
// Agentic Mode switched off since the timer was armed: fire nothing. The
// schedules stay in the DB; initialize_deferred / the AGENTIC tab re-arm
// them once it is back on.
if (!agentic_mode_enabled()) {
apply_schedule_due(0);
return;
}
// Woke for the periodic re-check rather than a due schedule: re-arm from
// the cached time, no Python. (1 s slack absorbs timer coarseness.)
if (QDateTime::currentMSecsSinceEpoch() + 1000 < next_schedule_due_ms_) {
rearm_schedule_timer();
return;
}
tick_schedules();
}
// ── Library inspection (Phase 3 management UI) ───────────────────────────────
QString AgentService::skills_list() {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_skills_list"), {}, {}, [self](bool ok, QJsonObject result) {
if (!self || !ok)
return;
emit self->skills_listed(result.value("skills").toArray());
});
return req_id;
}
QString AgentService::skill_delete(const QString& skill_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject p;
p["skill_id"] = skill_id;
run_python_stdin(QStringLiteral("agentic_skill_delete"), p, {}, [](bool, QJsonObject) {});
return req_id;
}
QString AgentService::archival_list(const QString& user_id, const QString& type) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject p;
if (!user_id.isEmpty())
p["user_id"] = user_id;
if (!type.isEmpty())
p["type"] = type;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_memory_list"), p, {}, [self](bool ok, QJsonObject result) {
if (!self || !ok)
return;
emit self->archival_listed(result.value("memories").toArray());
});
return req_id;
}
QString AgentService::archival_delete(const QString& memory_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject p;
p["memory_id"] = memory_id;
run_python_stdin(QStringLiteral("agentic_memory_delete"), p, {}, [](bool, QJsonObject) {});
return req_id;
}
QString AgentService::reflexion_list() {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_reflexion_list"), {}, {}, [self](bool ok, QJsonObject result) {
if (!self || !ok)
return;
emit self->reflexion_listed(result.value("reflections").toArray());
});
return req_id;
}
QString AgentService::pause_task(const QString& task_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["task_id"] = task_id;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_pause_task"), params, {},
[self, task_id, req_id](bool ok, QJsonObject result) {
if (!self || !ok)
return;
QJsonObject evt{{"kind", "control_ack"},
{"task_id", task_id},
{"request_id", req_id},
{"signal", result.value("signal").toString("pause_requested")}};
emit self->task_event(task_id, evt);
});
return req_id;
}
QString AgentService::cancel_task(const QString& task_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["task_id"] = task_id;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("agentic_cancel_task"), params, {},
[self, task_id, req_id](bool ok, QJsonObject result) {
if (!self || !ok)
return;
QJsonObject evt{{"kind", "control_ack"},
{"task_id", task_id},
{"request_id", req_id},
{"signal", result.value("signal").toString("cancel_requested")}};
emit self->task_event(task_id, evt);
});
return req_id;
}
QString AgentService::list_tasks(const QString& status_filter, int limit) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
if (!status_filter.isEmpty())
params["status"] = status_filter;
params["limit"] = limit;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("list_tasks"), params, {}, [self](bool ok, QJsonObject result) {
if (!self)
return;
if (ok)
emit self->tasks_listed(result.value("tasks").toArray());
else
emit self->error_occurred("list_tasks", result["error"].toString());
});
return req_id;
}
QString AgentService::get_task(const QString& task_id) {
const QString req_id = QUuid::createUuid().toString(QUuid::WithoutBraces);
QJsonObject params;
params["task_id"] = task_id;
QPointer<AgentService> self = this;
run_python_stdin(QStringLiteral("get_task"), params, {}, [self](bool ok, QJsonObject result) {
if (!self)
return;
if (ok)
emit self->task_loaded(result.value("task").toObject());
else
emit self->error_occurred("get_task", result["error"].toString());
});
return req_id;
}
} // namespace fincept::services