v0.8.7: tool capability metadata, in-process engine, Qt app, Android engine
The engine can be embedded now instead of only driven from a terminal: the same objects link into a Qt front end (app/) that owns a cst_agent_t inside its own process -- no port, no token, no second process -- and that front end now runs on the desktop and, engine-side, on the phone. Capability metadata (include/cst_tools.h, src/tools/registry.c): - cst_tool_def_t gains perm_name, platforms and available (a probe that returns a reason), so a permission is addressable by name and a tool can say why it cannot run here. - cst_platform_name(), cst_tool_platform_ok(), cst_tool_available(), cst_tool_meta_reload(), cst_tool_perm_name() and CST_PLAT_DESKTOP[]. - cst_tool_register() may take over a built-in name that is not runnable on this platform, so a front end replaces it with its own implementation. - the registry entries carry their class (delete_file -> "delete"), the desktop clipboard tools carry a clipboard probe; find/active/run gate on it. - /api/settings.tools[] exposes perm_name, platforms, available, why and the declared parameters. Engine as a library (Makefile, CMakeLists.txt): - libcstcore.a from the CORE_OBJ set, and a CMake cstcore target shared by the CLI and by app/ (-DCST_BUILD_APP=ON): the engine is compiled once. - Android branch for the vendored sashidown: a per-ABI archive built with the NDK's aarch64-linux-android24-clang wrapper, because CMake's compiler is plain clang and keeps --target/--sysroot in its own variables. Qt front end (app/, new): - AgentCore wraps one cst_agent_t: turns run on a worker thread, every cst_agent_hooks_t callback becomes a Qt signal, and the two hooks that need an answer (on_permission, on_ask_user) block the worker until the GUI replies; mode, approval and plan mode go through the engine's config. - ToolProvider hands the front end's tools to the engine (owner "app:*"); the Linux one is notification_send with a probe for notify-send/D-Bus. - Main.qml: transcript, tool blocks, consent dialog (Deny/Once/Always -> CST_PERM_*), ask_user, mode switch, Esc to cancel; --selftest stays headless and runs the embedding checks without QML. Android (scripts/, docs/android.md, new): - scripts/build_third_party_android.sh builds static mbedTLS + libcurl for an ABI (CA path /system/etc/security/cacerts); build_android.sh builds cst-agent, libcstcore.a and the test binaries for the phone, can push them and run the whole suite there. - sandbox_exec.c keeps the plain exec path on Android: the seccomp supervisor compiled in and the probe reported "seccomp", but writes outside the workspace were not denied on the device -- claiming a sandbox that does not hold is worse than reporting none. - tests/test_diff.c compares layouts only against real GNU diffutils: toybox's diff prints the same hunk header with its own hunk/context rules. Tests: test_tool_meta (metadata, platform gate, probe reasons, takeover of a built-in name) and test_embed (in-process embedding contract) are new; the existing registry/llm_body assertions now follow availability. 38 test binaries pass on the host, 36/36 on arm64-v8a Android 16, cst-app-selftest passes in both the standalone app/ build and the repo build. Version 0.8.7.
This commit is contained in:
@@ -0,0 +1,283 @@
|
||||
#include "AgentCore.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QThread>
|
||||
|
||||
/* --- the worker thread --------------------------------------------------- */
|
||||
|
||||
/* One turn: the whole cst_agent_run_turn_ex() call, on its own thread. The
|
||||
* prompt is kept here so the pointer stays valid for the run. */
|
||||
class Turn : public QThread {
|
||||
public:
|
||||
Turn(AgentCore *owner, const QString &prompt)
|
||||
: QThread(owner), m_owner(owner), m_prompt(prompt.toUtf8()) {}
|
||||
|
||||
protected:
|
||||
void run() override {
|
||||
char err[512] = "";
|
||||
int rc = cst_agent_run_turn_ex(m_owner->m_agent, m_prompt.constData(),
|
||||
&m_owner->m_hooks, err, sizeof(err));
|
||||
m_owner->finishTurn(rc, QString::fromUtf8(err));
|
||||
}
|
||||
|
||||
private:
|
||||
AgentCore *m_owner;
|
||||
QByteArray m_prompt;
|
||||
};
|
||||
|
||||
/* --- lifetime ------------------------------------------------------------ */
|
||||
|
||||
AgentCore::AgentCore(QObject *parent) : QObject(parent) {
|
||||
memset(&m_cfg, 0, sizeof(m_cfg));
|
||||
memset(&m_hooks, 0, sizeof(m_hooks));
|
||||
m_hooks.on_status = hookStatus;
|
||||
m_hooks.on_assistant_delta = hookAssistant;
|
||||
m_hooks.on_think_delta = hookThink;
|
||||
m_hooks.on_tool_event = hookToolEvent;
|
||||
m_hooks.on_tool_result = hookToolResult;
|
||||
m_hooks.on_todo = hookTodo;
|
||||
m_hooks.on_permission = hookPermission;
|
||||
m_hooks.on_ask_user = hookAskUser;
|
||||
m_hooks.userdata = this;
|
||||
}
|
||||
|
||||
AgentCore::~AgentCore() { close(); }
|
||||
|
||||
bool AgentCore::open(const QString &workspace, const QString &provider,
|
||||
const QString &model, const QString &apiKey,
|
||||
QString *err) {
|
||||
close();
|
||||
QDir dir(workspace);
|
||||
if (!dir.exists() && !dir.mkpath(".")) {
|
||||
if (err)
|
||||
*err = QStringLiteral("cannot create %1").arg(workspace);
|
||||
return false;
|
||||
}
|
||||
const QByteArray ws = QFileInfo(workspace).absoluteFilePath().toUtf8();
|
||||
snprintf(m_cfg.workspace_root, sizeof(m_cfg.workspace_root), "%s",
|
||||
ws.constData());
|
||||
m_workspace = QString::fromUtf8(ws);
|
||||
if (!provider.isEmpty())
|
||||
snprintf(m_cfg.provider, sizeof(m_cfg.provider), "%s",
|
||||
provider.toUtf8().constData());
|
||||
if (!model.isEmpty())
|
||||
snprintf(m_cfg.model, sizeof(m_cfg.model), "%s", model.toUtf8().constData());
|
||||
if (!apiKey.isEmpty())
|
||||
snprintf(m_cfg.api_key, sizeof(m_cfg.api_key), "%s",
|
||||
apiKey.toUtf8().constData());
|
||||
/* The GUI answers itself: never let the engine decide behind its back. */
|
||||
m_cfg.auto_approve = 0;
|
||||
m_cfg.headless = 0;
|
||||
if (!m_cfg.mode[0])
|
||||
snprintf(m_cfg.mode, sizeof(m_cfg.mode), "%s", CST_DEFAULT_MODE);
|
||||
m_agent = cst_agent_create(&m_cfg);
|
||||
if (!m_agent) {
|
||||
if (err)
|
||||
*err = QStringLiteral("cannot start the engine on %1").arg(m_workspace);
|
||||
return false;
|
||||
}
|
||||
/* The session file is created by the engine; attachments live next to it. */
|
||||
emit workspaceChanged();
|
||||
return true;
|
||||
}
|
||||
|
||||
void AgentCore::close() {
|
||||
if (!m_agent)
|
||||
return;
|
||||
if (m_running) {
|
||||
cst_agent_request_cancel(m_agent);
|
||||
answerPermission(CST_PERM_DENY);
|
||||
if (m_turn)
|
||||
m_turn->wait(15000);
|
||||
}
|
||||
m_closing = true;
|
||||
cst_agent_destroy(m_agent);
|
||||
m_agent = nullptr;
|
||||
m_closing = false;
|
||||
setRunning(false);
|
||||
m_workspace.clear();
|
||||
emit workspaceChanged();
|
||||
}
|
||||
|
||||
/* --- turns --------------------------------------------------------------- */
|
||||
|
||||
void AgentCore::send(const QString &prompt) {
|
||||
if (!m_agent || m_running || prompt.trimmed().isEmpty())
|
||||
return;
|
||||
setRunning(true);
|
||||
m_turn = new Turn(this, prompt);
|
||||
m_turn->start();
|
||||
}
|
||||
|
||||
void AgentCore::cancel() {
|
||||
if (m_agent)
|
||||
cst_agent_request_cancel(m_agent);
|
||||
}
|
||||
|
||||
void AgentCore::finishTurn(int rc, const QString &err) {
|
||||
Turn *t = static_cast<Turn *>(sender());
|
||||
post([this, rc, err] {
|
||||
setRunning(false);
|
||||
emit turnFinished(rc, err);
|
||||
});
|
||||
if (t) {
|
||||
t->wait();
|
||||
t->deleteLater();
|
||||
}
|
||||
m_turn = nullptr;
|
||||
}
|
||||
|
||||
void AgentCore::setRunning(bool on) {
|
||||
if (m_running == on)
|
||||
return;
|
||||
m_running = on;
|
||||
emit runningChanged();
|
||||
}
|
||||
|
||||
/* --- consent ------------------------------------------------------------- */
|
||||
|
||||
void AgentCore::answerPermission(int choice) {
|
||||
QMutexLocker lock(&m_askMu);
|
||||
if (!m_permPending)
|
||||
return;
|
||||
m_permAnswer = choice;
|
||||
m_permPending = false;
|
||||
m_askCv.wakeAll();
|
||||
}
|
||||
|
||||
void AgentCore::answerQuestion(const QString &answer) {
|
||||
QMutexLocker lock(&m_askMu);
|
||||
if (!m_questionPending)
|
||||
return;
|
||||
m_answer = answer.toUtf8();
|
||||
m_questionPending = false;
|
||||
m_askCv.wakeAll();
|
||||
}
|
||||
|
||||
int AgentCore::hookPermission(const char *tool, const char *detail,
|
||||
const char *preview, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
if (!self || self->m_closing)
|
||||
return CST_PERM_DENY;
|
||||
if (self->m_autoApprove)
|
||||
return CST_PERM_ONCE;
|
||||
QMutexLocker lock(&self->m_askMu);
|
||||
self->m_permAnswer = CST_PERM_DENY;
|
||||
self->m_permPending = true;
|
||||
const QString t = QString::fromUtf8(tool ? tool : "");
|
||||
const QString d = QString::fromUtf8(detail ? detail : "");
|
||||
const QString p = QString::fromUtf8(preview ? preview : "");
|
||||
self->post([self, t, d, p] { emit self->permissionRequested(t, d, p); });
|
||||
while (self->m_permPending && !self->m_closing)
|
||||
self->m_askCv.wait(&self->m_askMu);
|
||||
self->m_permPending = false;
|
||||
return self->m_permAnswer;
|
||||
}
|
||||
|
||||
int AgentCore::hookAskUser(const char *question, const char *options, char *ans,
|
||||
size_t ans_sz, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
if (!self || self->m_closing)
|
||||
return -1;
|
||||
if (self->m_autoApprove)
|
||||
return -1;
|
||||
QMutexLocker lock(&self->m_askMu);
|
||||
self->m_questionPending = true;
|
||||
self->m_answer.clear();
|
||||
const QString q = QString::fromUtf8(question ? question : "");
|
||||
const QString o = QString::fromUtf8(options ? options : "");
|
||||
self->post([self, q, o] { emit self->questionAsked(q, o); });
|
||||
while (self->m_questionPending && !self->m_closing)
|
||||
self->m_askCv.wait(&self->m_askMu);
|
||||
if (self->m_closing)
|
||||
return -1;
|
||||
snprintf(ans, ans_sz, "%s", self->m_answer.constData());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* --- settings ------------------------------------------------------------ */
|
||||
|
||||
void AgentCore::setMode(const QString &mode) {
|
||||
const QByteArray m = mode.toUtf8();
|
||||
if (!cst_mode_valid(m.constData()))
|
||||
return;
|
||||
snprintf(m_cfg.mode, sizeof(m_cfg.mode), "%s", m.constData());
|
||||
if (m_agent)
|
||||
snprintf(cst_agent_config_mut(m_agent)->mode,
|
||||
sizeof(cst_agent_config_mut(m_agent)->mode), "%s",
|
||||
m.constData());
|
||||
emit modeChanged();
|
||||
}
|
||||
|
||||
void AgentCore::setApproval(int approval) {
|
||||
m_cfg.approval = approval;
|
||||
if (m_agent)
|
||||
cst_agent_config_mut(m_agent)->approval = approval;
|
||||
}
|
||||
|
||||
void AgentCore::setPlanMode(bool on) {
|
||||
m_cfg.plan_mode = on ? 1 : 0;
|
||||
if (m_agent)
|
||||
cst_agent_config_mut(m_agent)->plan_mode = m_cfg.plan_mode;
|
||||
}
|
||||
|
||||
/* --- tools the front end provides ---------------------------------------- */
|
||||
|
||||
bool AgentCore::registerTool(const cst_tool_def_t *def) {
|
||||
if (!def || cst_tool_register(def) != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void AgentCore::unregisterOwner(const QString &owner) {
|
||||
const QByteArray o = owner.toUtf8();
|
||||
if (cst_tool_unregister_owner(o.constData()) > 0)
|
||||
cst_tool_meta_reload();
|
||||
}
|
||||
|
||||
/* --- hook trampolines ---------------------------------------------------- */
|
||||
|
||||
void AgentCore::hookStatus(const char *msg, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString m = QString::fromUtf8(msg ? msg : "");
|
||||
self->post([self, m] { emit self->statusChanged(m); });
|
||||
}
|
||||
|
||||
void AgentCore::hookAssistant(const char *text, size_t len, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString t = QString::fromUtf8(QByteArray(text, static_cast<int>(len)));
|
||||
self->post([self, t] { emit self->assistantDelta(t); });
|
||||
}
|
||||
|
||||
void AgentCore::hookThink(const char *text, size_t len, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString t = QString::fromUtf8(QByteArray(text, static_cast<int>(len)));
|
||||
self->post([self, t] { emit self->thinkDelta(t); });
|
||||
}
|
||||
|
||||
void AgentCore::hookToolEvent(const char *phase, const ctl_tool_call_t *call,
|
||||
const char *detail, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString p = QString::fromUtf8(phase ? phase : "");
|
||||
const QString n = QString::fromUtf8(call ? call->name : "");
|
||||
const QString d = QString::fromUtf8(detail ? detail : "");
|
||||
self->post([self, p, n, d] { emit self->toolEvent(p, n, d); });
|
||||
}
|
||||
|
||||
void AgentCore::hookToolResult(const ctl_tool_call_t *call, const char *out,
|
||||
size_t len, int exit_code, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString n = QString::fromUtf8(call ? call->name : "");
|
||||
QString o = QString::fromUtf8(QByteArray(out, static_cast<int>(len)));
|
||||
if (o.size() > 4000)
|
||||
o = o.left(4000) + QStringLiteral("\n… (truncated for the UI)");
|
||||
self->post([self, n, exit_code, o] { emit self->toolResult(n, exit_code, o); });
|
||||
}
|
||||
|
||||
void AgentCore::hookTodo(const char *text, void *ud) {
|
||||
AgentCore *self = static_cast<AgentCore *>(ud);
|
||||
const QString t = QString::fromUtf8(text ? text : "");
|
||||
self->post([self, t] { emit self->todoChanged(t); });
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/* AgentCore: the Qt wrapper around one cst_agent_t.
|
||||
*
|
||||
* The engine runs turns on a worker thread; every cst_agent_hooks_t callback
|
||||
* is turned into a Qt signal, and the two hooks that need an answer
|
||||
* (on_permission, on_ask_user) block the worker until the GUI replies. No
|
||||
* HTTP, no socket: the GUI owns the engine in its own process. */
|
||||
|
||||
#ifndef CST_APP_AGENTCORE_H
|
||||
#define CST_APP_AGENTCORE_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QMutex>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QWaitCondition>
|
||||
|
||||
#include "cst_agent.h"
|
||||
#include "cst_tools.h"
|
||||
|
||||
class QThread;
|
||||
|
||||
class AgentCore : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(bool running READ running NOTIFY runningChanged)
|
||||
Q_PROPERTY(QString workspace READ workspace NOTIFY workspaceChanged)
|
||||
Q_PROPERTY(QString mode READ mode NOTIFY modeChanged)
|
||||
|
||||
public:
|
||||
explicit AgentCore(QObject *parent = nullptr);
|
||||
~AgentCore() override;
|
||||
|
||||
/* Start the engine on a workspace. provider/model/apiKey may be empty to
|
||||
* fall back to the saved credentials and the provider's default model. */
|
||||
bool open(const QString &workspace, const QString &provider,
|
||||
const QString &model, const QString &apiKey, QString *err);
|
||||
void close();
|
||||
|
||||
bool running() const { return m_running; }
|
||||
QString workspace() const { return m_workspace; }
|
||||
QString mode() const { return QString::fromUtf8(m_cfg.mode); }
|
||||
|
||||
/* The engine, for the parts that need it (tool registration). */
|
||||
cst_agent_t *agent() const { return m_agent; }
|
||||
const cst_agent_config_t *config() const { return &m_cfg; }
|
||||
|
||||
/* Ask a question; emits the streaming signals, then turnFinished(). */
|
||||
Q_INVOKABLE void send(const QString &prompt);
|
||||
Q_INVOKABLE void cancel();
|
||||
|
||||
/* Consent: answers map to CST_PERM_*. */
|
||||
Q_INVOKABLE void answerPermission(int choice);
|
||||
Q_INVOKABLE void answerQuestion(const QString &answer);
|
||||
|
||||
Q_INVOKABLE void setMode(const QString &mode); /* coding | general */
|
||||
Q_INVOKABLE void setApproval(int approval); /* cst_approval_t */
|
||||
Q_INVOKABLE void setPlanMode(bool on);
|
||||
|
||||
/* Tools the front end implements itself. The engine copies the definition
|
||||
* (strings included), so a stack value is fine; ud must outlive it.
|
||||
* owner is what unregisterOwner() later matches. */
|
||||
bool registerTool(const cst_tool_def_t *def);
|
||||
void unregisterOwner(const QString &owner);
|
||||
/* Re-probe platform tools after a service appeared or went away. */
|
||||
void reloadToolMeta() { cst_tool_meta_reload(); }
|
||||
|
||||
/* Answer every consent question with "once" (the C smoke test, headless
|
||||
* runs, a --yes flag). */
|
||||
void setAutoApprove(bool on) { m_autoApprove = on; }
|
||||
|
||||
signals:
|
||||
void statusChanged(const QString &text);
|
||||
void assistantDelta(const QString &text);
|
||||
void thinkDelta(const QString &text);
|
||||
void toolEvent(const QString &phase, const QString &name,
|
||||
const QString &detail);
|
||||
void toolResult(const QString &name, int exitCode, const QString &output);
|
||||
void todoChanged(const QString &text);
|
||||
void permissionRequested(const QString &tool, const QString &detail,
|
||||
const QString &preview);
|
||||
void questionAsked(const QString &question, const QString &options);
|
||||
void turnFinished(int rc, const QString &err);
|
||||
void runningChanged();
|
||||
void workspaceChanged();
|
||||
void modeChanged();
|
||||
|
||||
private:
|
||||
friend class Turn;
|
||||
void finishTurn(int rc, const QString &err);
|
||||
void setRunning(bool on);
|
||||
|
||||
/* Hook trampolines (C, run on the worker thread). */
|
||||
static void hookStatus(const char *msg, void *ud);
|
||||
static void hookAssistant(const char *text, size_t len, void *ud);
|
||||
static void hookThink(const char *text, size_t len, void *ud);
|
||||
static void hookToolEvent(const char *phase, const ctl_tool_call_t *call,
|
||||
const char *detail, void *ud);
|
||||
static void hookToolResult(const ctl_tool_call_t *call, const char *out,
|
||||
size_t len, int exit_code, void *ud);
|
||||
static void hookTodo(const char *text, void *ud);
|
||||
static int hookPermission(const char *tool, const char *detail,
|
||||
const char *preview, void *ud);
|
||||
static int hookAskUser(const char *question, const char *options, char *ans,
|
||||
size_t ans_sz, void *ud);
|
||||
/* Post a lambda onto the GUI thread. */
|
||||
template <typename F>
|
||||
void post(F f) {
|
||||
QMetaObject::invokeMethod(this, f, Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
cst_agent_t *m_agent = nullptr;
|
||||
cst_agent_config_t m_cfg;
|
||||
cst_agent_hooks_t m_hooks;
|
||||
QString m_workspace;
|
||||
QThread *m_turn = nullptr;
|
||||
bool m_running = false;
|
||||
bool m_closing = false;
|
||||
|
||||
/* consent handshake between the worker and the GUI thread */
|
||||
QMutex m_askMu;
|
||||
QWaitCondition m_askCv;
|
||||
int m_permAnswer = CST_PERM_DENY;
|
||||
bool m_permPending = false;
|
||||
QString m_question;
|
||||
QByteArray m_answer;
|
||||
bool m_questionPending = false;
|
||||
bool m_autoApprove = false;
|
||||
};
|
||||
|
||||
#endif /* CST_APP_AGENTCORE_H */
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "ToolProvider.h"
|
||||
|
||||
#include "AgentCore.h"
|
||||
|
||||
namespace app {
|
||||
|
||||
/* Keep these in one place: every platform tool of the front end uses one of
|
||||
* them, so the engine's availability gate and the policy UI agree. */
|
||||
const char *const kDesktopOnly[] = {"desktop", NULL};
|
||||
const char *const kAndroidOnly[] = {"android", NULL};
|
||||
|
||||
int registerPlatformTools(AgentCore *core) {
|
||||
if (!core)
|
||||
return 0;
|
||||
int n = 0;
|
||||
#if defined(__ANDROID__)
|
||||
n += platformRegisterAndroid(core);
|
||||
#elif defined(__APPLE__)
|
||||
n += platformRegisterMac(core);
|
||||
#elif defined(_WIN32)
|
||||
n += platformRegisterWindows(core);
|
||||
#elif defined(__linux__)
|
||||
n += platformRegisterLinux(core);
|
||||
#endif
|
||||
/* A service may have appeared or gone since the last probe (a desktop
|
||||
* session starting, the notification daemon coming up). */
|
||||
cst_tool_meta_reload();
|
||||
return n;
|
||||
}
|
||||
|
||||
void unregisterPlatformTools(AgentCore *core) {
|
||||
if (!core)
|
||||
return;
|
||||
core->unregisterOwner(QStringLiteral("app:linux"));
|
||||
core->unregisterOwner(QStringLiteral("app:windows"));
|
||||
core->unregisterOwner(QStringLiteral("app:macos"));
|
||||
core->unregisterOwner(QStringLiteral("app:android"));
|
||||
}
|
||||
|
||||
} // namespace app
|
||||
@@ -0,0 +1,59 @@
|
||||
/* How the front end hands a tool to the engine.
|
||||
*
|
||||
* A tool implemented in C++ is an ordinary cst_tool_def_t: the engine owns a
|
||||
* copy of the definition, so a static (or stack) value is enough, and
|
||||
* `ud`/`run_ex` keep pointing at the front end's state. The callback runs on
|
||||
* the turn's worker thread -- touch Qt objects only through queued signals.
|
||||
*
|
||||
* See app/src/platform/linux/NotifyTool.cpp for a worked example, and
|
||||
* tests/test_embed.c for the same contract without Qt.
|
||||
*/
|
||||
|
||||
#ifndef CST_APP_TOOLPROVIDER_H
|
||||
#define CST_APP_TOOLPROVIDER_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
#include "cst_tools.h"
|
||||
|
||||
/* The engine wrapper of the front end (core/AgentCore.h). Only a pointer
|
||||
* travels through this header, so the class stays incomplete here. */
|
||||
class AgentCore;
|
||||
|
||||
namespace app {
|
||||
|
||||
/* Fill a definition in one place, so every front-end tool carries the same
|
||||
* metadata (class + policy name + platform list + probe). */
|
||||
inline void setMeta(cst_tool_def_t *def, const char *name, const char *desc,
|
||||
cst_tool_perm_t perm, const char *perm_name,
|
||||
const char *const *platforms,
|
||||
int (*available)(char *, size_t)) {
|
||||
def->name = name;
|
||||
def->desc = desc;
|
||||
def->perm = perm;
|
||||
def->perm_name = perm_name;
|
||||
def->platforms = platforms;
|
||||
def->available = available;
|
||||
}
|
||||
|
||||
/* Tools that only work on the phone. */
|
||||
extern const char *const kAndroidOnly[];
|
||||
/* Tools that only work on a desktop (linux / win / macos). */
|
||||
extern const char *const kDesktopOnly[];
|
||||
|
||||
/* The platform tools this app provides. Called once the engine exists;
|
||||
* returns how many were registered. */
|
||||
int registerPlatformTools(AgentCore *core);
|
||||
/* Drop them again (they belong to the owners "app:*"). */
|
||||
void unregisterPlatformTools(AgentCore *core);
|
||||
|
||||
/* One entry point per platform, implemented by the file under
|
||||
* src/platform/<os>/; ToolProvider.cpp picks one at compile time. */
|
||||
int platformRegisterLinux(AgentCore *core);
|
||||
int platformRegisterMac(AgentCore *core);
|
||||
int platformRegisterWindows(AgentCore *core);
|
||||
int platformRegisterAndroid(AgentCore *core);
|
||||
|
||||
} // namespace app
|
||||
|
||||
#endif /* CST_APP_TOOLPROVIDER_H */
|
||||
@@ -0,0 +1,155 @@
|
||||
/* cst-agent-app: the Qt front end.
|
||||
*
|
||||
* cst-agent-app --workspace DIR [--provider p] [--model m] [--api-key k]
|
||||
* cst-agent-app --selftest embedding checks, no window, no network
|
||||
*
|
||||
* The engine runs in this process (see app/README.md); nothing listens on a
|
||||
* port and no second process is started. */
|
||||
|
||||
#include <QCommandLineParser>
|
||||
#include <QCoreApplication>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QGuiApplication>
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QQmlContext>
|
||||
#include <QStandardPaths>
|
||||
#include <QTemporaryDir>
|
||||
#include <QTextStream>
|
||||
#include <QUrl>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "core/AgentCore.h"
|
||||
#include "core/ToolProvider.h"
|
||||
#include "cst_version.h"
|
||||
|
||||
namespace {
|
||||
|
||||
int runSelftest() {
|
||||
QTextStream out(stdout);
|
||||
int bad = 0;
|
||||
QTemporaryDir tmp;
|
||||
if (!tmp.isValid()) {
|
||||
out << "selftest: cannot create a scratch dir\n";
|
||||
return 1;
|
||||
}
|
||||
AgentCore core;
|
||||
QString err;
|
||||
if (!core.open(tmp.path(), QStringLiteral("deepseek"),
|
||||
QStringLiteral("deepseek-flash"), QStringLiteral("test-key"),
|
||||
&err)) {
|
||||
out << "selftest: engine did not start: " << err << "\n";
|
||||
return 1;
|
||||
}
|
||||
out << "selftest: engine started in-process\n";
|
||||
if (core.agent() == nullptr) {
|
||||
out << "selftest: no agent handle\n";
|
||||
return 1;
|
||||
}
|
||||
/* the front end's own tools go through the engine's registry */
|
||||
const int n = app::registerPlatformTools(&core);
|
||||
out << "selftest: platform tools registered: " << n << "\n";
|
||||
const cst_tool_def_t *t = cst_tool_find("notification_send");
|
||||
if (!t) {
|
||||
out << "selftest: notification_send is not in the registry\n";
|
||||
bad++;
|
||||
} else {
|
||||
if (t->owner == nullptr || strncmp(t->owner, "app:", 4) != 0) {
|
||||
out << "selftest: notification_send has no app owner\n";
|
||||
bad++;
|
||||
}
|
||||
char why[160] = "";
|
||||
const bool ok = cst_tool_available(t, why, sizeof(why)) == 0;
|
||||
out << "selftest: notification_send available=" << (ok ? "yes" : "no")
|
||||
<< (ok ? "" : QStringLiteral(" (%1)").arg(QString::fromUtf8(why)))
|
||||
<< "\n";
|
||||
}
|
||||
/* the mode comes from the engine, not from the UI */
|
||||
core.setMode(QStringLiteral("general"));
|
||||
if (core.mode() != QLatin1String("general")) {
|
||||
out << "selftest: mode did not stick\n";
|
||||
bad++;
|
||||
}
|
||||
app::unregisterPlatformTools(&core);
|
||||
if (cst_tool_find("notification_send") != nullptr) {
|
||||
out << "selftest: platform tools were not dropped\n";
|
||||
bad++;
|
||||
}
|
||||
core.close();
|
||||
out << (bad ? "selftest: FAILED\n" : "selftest: OK\n");
|
||||
out.flush();
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
/* --selftest stays headless: no window, no QML, no display needed. */
|
||||
bool selftest = false;
|
||||
for (int i = 1; i < argc; i++)
|
||||
if (strcmp(argv[i], "--selftest") == 0)
|
||||
selftest = true;
|
||||
if (selftest) {
|
||||
QCoreApplication app(argc, argv);
|
||||
return runSelftest();
|
||||
}
|
||||
|
||||
QGuiApplication app(argc, argv);
|
||||
QGuiApplication::setApplicationName(QStringLiteral("cst-agent-app"));
|
||||
QGuiApplication::setApplicationVersion(QStringLiteral(CST_VERSION));
|
||||
QGuiApplication::setOrganizationName(QStringLiteral("cst-agent"));
|
||||
|
||||
QCommandLineParser parser;
|
||||
parser.setApplicationDescription(
|
||||
QStringLiteral("CST-agent desktop front end (engine in-process)"));
|
||||
parser.addHelpOption();
|
||||
parser.addVersionOption();
|
||||
QCommandLineOption wsOpt({QStringLiteral("w"), QStringLiteral("workspace")},
|
||||
QStringLiteral("workspace directory"),
|
||||
QStringLiteral("dir"));
|
||||
QCommandLineOption providerOpt(QStringLiteral("provider"),
|
||||
QStringLiteral("provider name"),
|
||||
QStringLiteral("name"));
|
||||
QCommandLineOption modelOpt(QStringLiteral("model"),
|
||||
QStringLiteral("model name"), QStringLiteral("name"));
|
||||
QCommandLineOption planOpt(QStringLiteral("plan"),
|
||||
QStringLiteral("start in plan mode"));
|
||||
parser.addOption(wsOpt);
|
||||
parser.addOption(providerOpt);
|
||||
parser.addOption(modelOpt);
|
||||
parser.addOption(planOpt);
|
||||
parser.process(app);
|
||||
|
||||
QString ws = parser.value(wsOpt);
|
||||
if (ws.isEmpty())
|
||||
ws = QDir::currentPath();
|
||||
ws = QFileInfo(ws).absoluteFilePath();
|
||||
|
||||
AgentCore core;
|
||||
QString err;
|
||||
if (!core.open(ws, parser.value(providerOpt), parser.value(modelOpt),
|
||||
QString(), &err)) {
|
||||
QTextStream(stderr) << "cannot start the engine: " << err << "\n";
|
||||
return 1;
|
||||
}
|
||||
app::registerPlatformTools(&core); /* the app's own tools */
|
||||
if (parser.isSet(planOpt))
|
||||
core.setPlanMode(true);
|
||||
|
||||
QQmlApplicationEngine engine;
|
||||
engine.rootContext()->setContextProperty(QStringLiteral("agent"), &core);
|
||||
const QUrl url(QStringLiteral("qrc:/qt/qml/CstAgent/qml/Main.qml"));
|
||||
QObject::connect(
|
||||
&engine, &QQmlApplicationEngine::objectCreated, &app,
|
||||
[url](QObject *obj, const QUrl &objUrl) {
|
||||
if (!obj && url == objUrl)
|
||||
QCoreApplication::exit(-1);
|
||||
},
|
||||
Qt::QueuedConnection);
|
||||
engine.load(url);
|
||||
if (engine.rootObjects().isEmpty())
|
||||
return 1;
|
||||
return app.exec();
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/* Platform tools on Linux, implemented by the app (not by the engine): they
|
||||
* exist exactly where the desktop service does, and the engine only ever sees
|
||||
* the capability -- platforms + probe decide whether the tool is offered. */
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QFileInfo>
|
||||
#include <QProcess>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "core/AgentCore.h"
|
||||
#include "core/ToolProvider.h"
|
||||
|
||||
namespace app {
|
||||
namespace {
|
||||
|
||||
/* whereis-style check without a shell: the same rule the engine uses for the
|
||||
* clipboard helpers. */
|
||||
bool haveProgram(const char *name) {
|
||||
QByteArray path = qgetenv("PATH");
|
||||
const QList<QByteArray> dirs = path.split(':');
|
||||
for (const QByteArray &d : dirs) {
|
||||
QByteArray dir = d.isEmpty() ? QByteArray(".") : d;
|
||||
QByteArray cand = dir + "/" + name;
|
||||
if (QFileInfo::exists(QString::fromLocal8Bit(cand)) &&
|
||||
QFileInfo(QString::fromLocal8Bit(cand)).isExecutable())
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* 0 when notifications can be shown; -1 with the reason otherwise. */
|
||||
int notifyProbe(char *why, size_t why_sz) {
|
||||
if (haveProgram("notify-send"))
|
||||
return 0;
|
||||
if (haveProgram("gdbus") && !qgetenv("DBUS_SESSION_BUS_ADDRESS").isEmpty())
|
||||
return 0;
|
||||
snprintf(why, why_sz,
|
||||
"no notification service (no notify-send, no D-Bus session bus)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *argOf(const ctl_tool_call_t *call, const char *key) {
|
||||
for (int i = 0; i < call->nargs; i++)
|
||||
if (strcmp(call->args[i].key, key) == 0)
|
||||
return call->args[i].value;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Runs on the turn's worker thread: no GUI objects here. */
|
||||
int notifyRun(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
|
||||
cst_tool_result_t *r, void *ud) {
|
||||
(void)ctx;
|
||||
(void)ud;
|
||||
const char *title = argOf(call, "title");
|
||||
const char *message = argOf(call, "message");
|
||||
if (!message || !message[0]) {
|
||||
const char *msg = "error: notification_send needs a message";
|
||||
r->out = strdup(msg);
|
||||
r->out_len = r->out ? strlen(msg) : 0;
|
||||
r->exit_code = 1;
|
||||
return 0;
|
||||
}
|
||||
QStringList args;
|
||||
if (title && title[0])
|
||||
args << QString::fromUtf8(title);
|
||||
else
|
||||
args << QStringLiteral("CST-agent");
|
||||
args << QString::fromUtf8(message);
|
||||
const int rc = QProcess::execute(QStringLiteral("notify-send"), args);
|
||||
const QByteArray text =
|
||||
(rc == 0 ? QByteArrayLiteral("notification sent")
|
||||
: QByteArrayLiteral("notify-send failed (rc=") +
|
||||
QByteArray::number(rc) + QByteArrayLiteral(")"));
|
||||
r->out = strdup(text.constData());
|
||||
r->out_len = r->out ? strlen(r->out) : 0;
|
||||
r->exit_code = rc == 0 ? 0 : 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Registered once; the engine keeps a copy until the owner is unregistered. */
|
||||
cst_tool_def_t g_notify;
|
||||
|
||||
} // namespace
|
||||
|
||||
int platformRegisterLinux(AgentCore *core) {
|
||||
static const cst_tool_param_t params[CST_TOOL_MAX_PARAMS] = {
|
||||
{"message", "string", 1, "text of the notification"},
|
||||
{"title", "string", 0, "title line (default: CST-agent)"},
|
||||
{nullptr, nullptr, 0, nullptr},
|
||||
{nullptr, nullptr, 0, nullptr},
|
||||
{nullptr, nullptr, 0, nullptr},
|
||||
{nullptr, nullptr, 0, nullptr}};
|
||||
memset(&g_notify, 0, sizeof(g_notify));
|
||||
setMeta(&g_notify, "notification_send",
|
||||
"Show a desktop notification (what the user sees outside the app).",
|
||||
CST_TP_ASK, "notify", kDesktopOnly, notifyProbe);
|
||||
memcpy(g_notify.params, params, sizeof(params));
|
||||
g_notify.run = nullptr;
|
||||
g_notify.run_ex = notifyRun;
|
||||
g_notify.ud = nullptr;
|
||||
g_notify.owner = "app:linux";
|
||||
return core->registerTool(&g_notify) ? 1 : 0;
|
||||
}
|
||||
|
||||
} // namespace app
|
||||
Reference in New Issue
Block a user