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:
WHC
2026-10-11 11:42:04 +08:00
parent e0b0eddf3a
commit 5ba215b36c
28 changed files with 2452 additions and 34 deletions
+102
View File
@@ -0,0 +1,102 @@
cmake_minimum_required(VERSION 3.16)
project(cst-agent-app LANGUAGES C CXX VERSION 0.1.0)
# The Qt front end (app/) embeds the C engine in-process: it links libcstcore
# and never opens a port. Two targets:
#
# cst-app-selftest pure C smoke test of the embedding path (no Qt), so the
# C side is still guarded on machines without Qt Quick
# cst-agent-app the GUI (Qt 6 Quick + QML), built when the Qt modules
# are there
#
# Standalone build (builds the engine from ../ too):
# cmake -S app -B build-app -DCMAKE_BUILD_TYPE=Debug && cmake --build build-app -j
# Inside the repo build (the parent defines the cstcore target, shared with the CLI):
# cmake -B build -DCST_BUILD_APP=ON && cmake --build build --target cst-agent-app
#
# Extra QML import paths, e.g. a Kirigami installed away from the Qt prefix:
# -DCST_APP_QML_IMPORT=... (added to QML2_IMPORT_PATH / the app's runtime)
option(CST_APP_GUI "build the Qt GUI (needs Qt6 Quick, Qml, QuickControls2)" ON)
option(CST_APP_SELFTEST "build the C embedding smoke test" ON)
# --- the engine ----------------------------------------------------------
# Used as a subproject (../CMakeLists.txt already defined cstcore, engine
# compiled once for CLI and app) or built here from the sources next door.
if(NOT TARGET cstcore)
set(CST_APP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/..")
include_directories("${CST_APP_ROOT}/include" "${CST_APP_ROOT}/vendor/cjson")
file(GLOB CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/*.c"
"${CST_APP_ROOT}/src/tools/*.c"
"${CST_APP_ROOT}/vendor/cjson/cJSON.c")
list(REMOVE_ITEM CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/main.c"
"${CST_APP_ROOT}/src/tui.c"
"${CST_APP_ROOT}/src/tui_stub.c"
"${CST_APP_ROOT}/src/textsel.c")
# The HTTP front end is not part of an in-process app: no server, no port.
list(REMOVE_ITEM CST_APP_CORE_SRC
"${CST_APP_ROOT}/src/net.c"
"${CST_APP_ROOT}/src/http_srv.c"
"${CST_APP_ROOT}/src/webui.c"
"${CST_APP_ROOT}/src/web_md.c")
if(EXISTS "${CST_APP_ROOT}/.gen/models_builtin.inc")
include_directories("${CST_APP_ROOT}/.gen")
endif()
add_library(cstcore STATIC ${CST_APP_CORE_SRC})
target_compile_definitions(cstcore PRIVATE CST_NO_WEBUI=1)
find_package(CURL REQUIRED)
find_package(Threads REQUIRED)
target_link_libraries(cstcore PUBLIC ${CURL_LIBRARIES} Threads::Threads m)
message(STATUS "app: building the engine from ${CST_APP_ROOT}")
else()
message(STATUS "app: linking the cstcore target of the parent build")
endif()
# --- the C smoke test ----------------------------------------------------
if(CST_APP_SELFTEST)
add_executable(cst-app-selftest tools/selftest.c)
target_link_libraries(cst-app-selftest PRIVATE cstcore)
enable_testing()
add_test(NAME cst-app-selftest COMMAND cst-app-selftest)
endif()
# --- the GUI -------------------------------------------------------------
if(CST_APP_GUI)
find_package(Qt6 6.4 COMPONENTS Core Gui Qml Quick QuickControls2 QUIET)
if(NOT Qt6_FOUND)
message(WARNING
"app: Qt 6 Quick/Qml not found, skipping cst-agent-app "
"(the C selftest still builds; install e.g. qt6.qtdeclarative / "
"qt6.qtquickcontrols2 and reconfigure)")
else()
qt_standard_project_setup()
# Qt 6.5+ policies: keep the module resource at :/qt/qml/<URI>/ (what
# main.cpp loads) and let CMake generate the qmldir of qml/ for us.
qt_policy(SET QTP0001 NEW)
qt_policy(SET QTP0004 NEW)
qt_add_executable(cst-agent-app
src/main.cpp
src/core/AgentCore.cpp
src/core/ToolProvider.cpp
src/platform/linux/NotifyTool.cpp)
target_include_directories(cst-agent-app PRIVATE
src "${CMAKE_CURRENT_SOURCE_DIR}/../include")
target_compile_definitions(cst-agent-app PRIVATE CST_APP_VERSION="${PROJECT_VERSION}")
if(CST_APP_QML_IMPORT)
target_compile_definitions(cst-agent-app PRIVATE
CST_APP_QML_IMPORT="${CST_APP_QML_IMPORT}")
endif()
target_link_libraries(cst-agent-app PRIVATE
Qt6::Core Qt6::Gui Qt6::Qml Qt6::Quick Qt6::QuickControls2 cstcore)
if(WIN32)
set_target_properties(cst-agent-app PROPERTIES WIN32_EXECUTABLE TRUE)
endif()
qt_add_qml_module(cst-agent-app
URI CstAgent
VERSION 1.0
QML_FILES qml/Main.qml)
endif()
endif()
+119
View File
@@ -0,0 +1,119 @@
# app/ — the Qt front end
CST-agent's GUI: **Qt 6 + QML + the C engine, in one process**. No HTTP
server, no port, no token, no second process — the app creates a `cst_agent_t`
directly and drives it through `cst_agent.h`.
```
app/ the GUI
src/main.cpp entry point, --workspace / --selftest
src/core/AgentCore.* QObject around cst_agent_t: turns, hooks, consent
src/core/ToolProvider.h how the front end hands tools to the engine
src/platform/<os>/ platform tools the app implements itself
qml/Main.qml the window (chat, tool runs, consent dialog)
tools/selftest.c C smoke test of the embedding path (no Qt)
```
## Build
```sh
# engine + GUI + C smoke test
cmake -S app -B build-app -DCMAKE_BUILD_TYPE=Debug
cmake --build build-app -j
QT_QPA_PLATFORM=offscreen ctest --test-dir build-app # cst-app-selftest
# the app alone
./build-app/cst-agent-app --workspace ~/notes
./build-app/cst-agent-app --selftest # same checks as the C test
```
The standalone build is the supported one: `app/CMakeLists.txt` uses the
`cstcore` target when the parent project defines one, and otherwise builds
the engine itself from `../src` (TUI, `main.c` and the HTTP front end
excluded). Wiring it into the repository's `CMakeLists.txt` as
`-DCST_APP=ON` is on the list below.
Needs Qt 6.4+ with **Quick / Qml / QuickControls2** (`qt6.qtdeclarative`,
`qt6.qtquickcontrols2` on Nix; the online installer's "Qt 6.x Desktop" on
Windows/macOS). Without them the configure step warns and builds only the C
smoke test — that is deliberate: the embedding path stays verifiable
everywhere. Kirigami is not required yet; `qml/Main.qml` uses Qt Quick
Controls and keeps the layout in Kirigami's shape (single column, cards,
navigation drawer) so swapping in `org.kde.kirigami` later is a QML-only
change. Point the app at a Kirigami outside the Qt prefix with
`-DCST_APP_QML_IMPORT=/path/to/qml`.
## Why in one process
The engine is a library, not a daemon: `libcstcore.a` (Makefile) / the
`cstcore` target (CMake). The app owns one `cst_agent_t` per window, so
there is no protocol to version, no socket to authenticate and no second
process to babysit — and the CLI, TUI and WebUI keep working off the same
source.
- `AgentCore::send()` runs `cst_agent_run_turn_ex()` on a worker thread;
the `cst_agent_hooks_t` callbacks turn into Qt signals (assistant deltas,
tool events, tool results, todo, turn end).
- Consent is a blocking hook: the worker waits on a `QWaitCondition`, the
GUI answers, the turn goes on. `CST_PERM_DENY / ONCE / ALWAYS_TOOL /
ALWAYS_PREFIX` map 1:1 onto the buttons, and `ALWAYS_*` still lands in
`.agent/permissions.json`, so a desktop decision is visible to the TUI.
- `cancel()` is `cst_agent_request_cancel()`; the turn unwinds as a normal
result, not an exception.
## Tools the app provides
A tool implemented in the front end is registered with `cst_tool_register()`
and the owner `app:<name>`, exactly like a plugin or MCP server would:
```c
cst_tool_def_t def = {0};
def.name = "notification_send";
def.desc = "Send a system notification.";
def.perm = CST_TP_ASK; /* class: drives the consent dialog */
def.perm_name = "notify"; /* policy: what the user is really granting */
def.platforms = ANDROID_ONLY; /* NULL = everywhere */
def.available = probe; /* 0 / -1 with a reason; cached */
def.run_ex = my_run;
def.ud = my_state;
def.owner = "app:android";
cst_tool_register(&def);
```
- `platforms` + `available` decide *whether* the tool exists here: an
Android-only tool never reaches the prompt or `tools[]` on Linux, and
`cst_tool_run()` refuses it with the reason if a model asks anyway.
- A front-end tool may take over the **name** of a built-in that cannot run
on this host (the Android clipboard replacing the desktop `xclip` one);
it may not shadow one that works.
- `cst_tool_unregister_owner("app:android")` drops them again — do it when a
platform service goes away, then `cst_tool_meta_reload()`.
- `setenv("CST_PLATFORM", ...)` overrides the detected host name (tests, a
launcher that knows better).
Note `run_ex` runs on the worker thread while the turn is going: touch the
GUI only through queued signals.
## Platform notes
| Platform | How the engine gets built | Platform tools |
|---|---|---|
| Linux | `cmake -S app -B build-app` (libcurl via pkg-config) | clipboard (shell helpers), notification (`notify-send` / D-Bus) |
| Windows | Qt's MinGW kit, `cmake -G Ninja -DCMAKE_PREFIX_PATH=<Qt>/lib/cmake`; the engine needs libcurl for Windows (see `docs/README-windows.md`) | notification via the WinRT/tray API, clipboard through the core's Win32 path |
| Android | engine compiled with the NDK inside the APK (`-DCST_TUI=0`, `CST_NO_WEBUI=1`); the app talks to Android APIs through Qt (JNI) | notification (Android), share sheet, clipboard, file picker |
| macOS | Qt from the installer, libcurl from the system | notification (`osascript`), clipboard (`pbpaste`/`pbcopy`) |
Android's long-term shape: the core lives in the APK (no Termux needed), the
platform tools are Kotlin/JNI behind the same `cst_tool_register()` contract.
The build flag that keeps Unix helpers out of the picture is
`CST_PLATFORM=android` (or the `__ANDROID__` detection inside the engine).
## Status
- [x] engine as a library (`libcstcore.a` / `cstcore`), in-process embed API
- [x] tool metadata: `perm_name`, `platforms`, `available`, shadowing rule
- [x] `AgentCore` (turns, cancel, consent, todo) and the C smoke test
- [ ] QML window against a real provider (needs Qt Quick)
- [ ] session list / switch, attachments, diff viewer, settings page
- [ ] Kirigami (Breeze look), tray, global shortcuts
- [ ] Android APK (engine in-process, JNI platform tools)
+229
View File
@@ -0,0 +1,229 @@
// The app window: chat on the left, tool runs and consent on top of it.
//
// Qt Quick Controls only, laid out the way Kirigami expects (single column,
// cards, drawer for navigation) so that swapping `import QtQuick.Controls`
// for `import org.kde.kirigami as Kirigami` and Page/Card wrappers is a QML
// change, not a rewrite.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
id: win
width: 980
height: 720
visible: true
title: "CST-agent — " + (agent.workspace.length ? agent.workspace : "no workspace")
ListModel { id: transcript }
header: ToolBar {
RowLayout {
anchors.fill: parent
Label {
text: agent.workspace.length ? agent.workspace : "(no workspace)"
elide: Text.ElideMiddle
Layout.fillWidth: true
}
BusyIndicator {
running: agent.running
visible: agent.running
implicitWidth: 24
implicitHeight: 24
}
ComboBox {
id: modeBox
model: ["coding", "general"]
currentIndex: agent.mode === "general" ? 1 : 0
onActivated: agent.setMode(model[currentIndex])
}
}
}
// ---- consent: the engine's on_permission hook waits for this ----
Dialog {
id: consent
anchors.centerIn: parent
width: Math.min(720, win.width - 40)
modal: true
property string tool: ""
property string detail: ""
property string preview: ""
title: "Allow " + tool + "?"
contentItem: ColumnLayout {
Label { text: consent.detail; wrapMode: Text.Wrap; Layout.fillWidth: true }
ScrollView {
Layout.fillWidth: true
Layout.preferredHeight: Math.min(300, previewText.implicitHeight + 16)
visible: consent.preview.length > 0
TextArea {
id: previewText
text: consent.preview
readOnly: true
font.family: "monospace"
wrapMode: TextArea.NoWrap
}
}
}
footer: DialogButtonBox {
Button { text: "Deny"; DialogButtonBox.buttonRole: DialogButtonBox.RejectRole }
Button { text: "Once"; DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole }
Button { text: "Always"; DialogButtonBox.buttonRole: DialogButtonBox.ActionRole }
onRejected: { agent.answerPermission(0); consent.close() }
onAccepted: { agent.answerPermission(1); consent.close() }
onClicked: function (button) {
if (button.text === "Always") { agent.answerPermission(2); consent.close() }
}
}
}
// ---- ask_user ----
Dialog {
id: question
anchors.centerIn: parent
width: Math.min(600, win.width - 40)
modal: true
property string text: ""
property string options: ""
title: "The agent asks"
contentItem: ColumnLayout {
Label { text: question.text; wrapMode: Text.Wrap; Layout.fillWidth: true }
Label {
visible: question.options.length > 0
text: question.options
wrapMode: Text.Wrap
Layout.fillWidth: true
opacity: 0.7
}
TextField { id: answerField; Layout.fillWidth: true; placeholderText: "your answer" }
}
footer: DialogButtonBox {
Button { text: "Send"; DialogButtonBox.buttonRole: DialogButtonBox.AcceptRole }
onAccepted: { agent.answerQuestion(answerField.text); question.close() }
}
}
ColumnLayout {
anchors.fill: parent
anchors.margins: 12
spacing: 8
ListView {
id: chat
Layout.fillWidth: true
Layout.fillHeight: true
model: transcript
clip: true
spacing: 8
delegate: Frame {
width: chat.width
background: Rectangle {
color: model.role === "user" ? "#2b579a22" : "#00000000"
border.color: "#88888833"
radius: 6
}
ColumnLayout {
width: parent.width
spacing: 2
Label {
text: model.role === "user" ? "You" : "Agent"
font.bold: true
opacity: 0.7
}
TextEdit {
text: model.text
readOnly: true
wrapMode: TextEdit.Wrap
selectByMouse: true
Layout.fillWidth: true
}
}
}
onCountChanged: positionViewAtEnd()
}
RowLayout {
Layout.fillWidth: true
TextArea {
id: composer
Layout.fillWidth: true
Layout.preferredHeight: 90
placeholderText: agent.running ? "… working (Esc cancels)"
: "Ask something (Enter sends, Shift+Enter for a new line)"
wrapMode: TextArea.Wrap
enabled: !agent.running
Keys.onPressed: function (ev) {
if (ev.key === Qt.Key_Return && !(ev.modifiers & Qt.ShiftModifier)) {
sendButton.clicked()
ev.accepted = true
}
}
}
ColumnLayout {
Button {
id: sendButton
text: "Send"
enabled: !agent.running && composer.text.trim().length > 0
onClicked: {
transcript.append({ role: "user", text: composer.text })
transcript.append({ role: "agent", text: "" })
agent.send(composer.text)
composer.text = ""
}
}
Button {
text: "Stop"
enabled: agent.running
onClicked: agent.cancel()
}
}
}
}
Shortcut { sequence: "Escape"; onActivated: agent.cancel() }
// ---- engine -> UI ----
function appendToAgent(text) {
if (transcript.count === 0)
transcript.append({ role: "agent", text: "" })
const last = transcript.count - 1
transcript.setProperty(last, "text", transcript.get(last).text + text)
}
Connections {
target: agent
function onAssistantDelta(text) { appendToAgent(text) }
function onStatusChanged(text) {
transcript.append({ role: "agent", text: "· " + text })
}
function onToolEvent(phase, name, detail) {
transcript.append({
role: "agent",
text: "[" + name + " " + phase + (detail.length ? ": " + detail : "") + "]"
})
}
function onToolResult(name, exitCode, output) {
transcript.append({
role: "agent",
text: "[" + name + " exit=" + exitCode + "]\n" + output
})
}
function onPermissionRequested(tool, detail, preview) {
consent.tool = tool
consent.detail = detail
consent.preview = preview
consent.open()
}
function onQuestionAsked(text, options) {
question.text = text
question.options = options
answerField.text = ""
question.open()
}
function onTurnFinished(rc, err) {
if (err.length)
transcript.append({ role: "agent", text: "error: " + err })
}
}
}
+283
View File
@@ -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); });
}
+129
View File
@@ -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 */
+40
View File
@@ -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
+59
View File
@@ -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 */
+155
View File
@@ -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();
}
+109
View File
@@ -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
+151
View File
@@ -0,0 +1,151 @@
/* The app's C smoke test: does the engine embed the way app/ needs it to?
*
* It links libcstcore.a (or the cstcore target) and runs without Qt, so the
* C side of the GUI stays verifiable on any machine -- including CI and the
* Android cross-build. `cst-agent-app --selftest` runs the same checks inside
* the real process. */
#define _POSIX_C_SOURCE 200809L
#include "cst_agent.h"
#include "cst_tools.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <process.h>
#include <direct.h>
#define getpid _getpid
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
static int failures;
#define CHECK(cond, what) \
do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, what); \
failures++; \
} \
} while (0)
/* A tool the app would implement (the Linux build uses notify-send; here it
* only has to prove the plumbing). */
static int ctx_runs;
static int app_tool_run(const cst_tool_ctx_t *ctx, const ctl_tool_call_t *call,
cst_tool_result_t *r, void *ud) {
(void)ctx;
(void)call;
(void)ud;
ctx_runs++;
r->out = strdup("app tool ran");
r->out_len = r->out ? strlen(r->out) : 0;
r->exit_code = 0;
return 0;
}
static int probe_missing(char *why, size_t why_sz) {
snprintf(why, why_sz, "the desktop service is not running");
return -1;
}
int main(void) {
char ws[1024];
snprintf(ws, sizeof(ws), "/tmp/cst-app-selftest-%d", (int)getpid());
#ifdef _WIN32
_mkdir(ws); /* the engine wants its workspace to exist */
#else
mkdir(ws, 0700);
#endif
cst_agent_config_t cfg;
memset(&cfg, 0, sizeof(cfg));
snprintf(cfg.workspace_root, sizeof(cfg.workspace_root), "%s", ws);
snprintf(cfg.session_path, sizeof(cfg.session_path), "%s/s.jsonl", ws);
snprintf(cfg.provider, sizeof(cfg.provider), "deepseek");
snprintf(cfg.model, sizeof(cfg.model), "deepseek-flash");
snprintf(cfg.api_base, sizeof(cfg.api_base), "https://api.deepseek.com/v1");
snprintf(cfg.api_key, sizeof(cfg.api_key), "test-key");
snprintf(cfg.mode, sizeof(cfg.mode), "general");
cfg.max_steps = 1;
cst_agent_t *a = cst_agent_create(&cfg);
CHECK(a != NULL, "the app can start an engine in its own process");
if (!a) {
fprintf(stderr, "cst-app-selftest: cannot start the engine\n");
return 1;
}
/* 1. a tool that exists here (no probe) is offered to the model */
cst_tool_def_t plain;
memset(&plain, 0, sizeof(plain));
plain.name = "app_ping";
plain.desc = "A tool the app provides.";
plain.perm = CST_TP_READ;
plain.run_ex = app_tool_run;
plain.owner = "app:selftest";
CHECK(cst_tool_register(&plain) == 0, "register an app tool");
const cst_tool_def_t *t = cst_tool_find("app_ping");
CHECK(t != NULL, "it is findable");
CHECK(t && cst_tool_active(cst_agent_config(a), t), "and it is offered");
ctl_tool_call_t call;
memset(&call, 0, sizeof(call));
snprintf(call.name, sizeof(call.name), "app_ping");
cst_tool_result_t res;
cst_tool_ctx_t ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.workspace_root = ws;
ctx.agent = a;
cst_tool_run(&ctx, &call, &res);
CHECK(ctx_runs == 1, "the app callback ran");
CHECK(res.out && strcmp(res.out, "app tool ran") == 0, "its result came back");
cst_tool_result_free(&res);
/* 2. a tool whose platform service is missing is never offered ... */
cst_tool_def_t missing;
memset(&missing, 0, sizeof(missing));
missing.name = "app_no_service";
missing.desc = "Needs a service that is not here.";
missing.perm = CST_TP_ASK;
missing.perm_name = "notify";
missing.available = probe_missing;
missing.run_ex = app_tool_run;
missing.owner = "app:selftest";
CHECK(cst_tool_register(&missing) == 0, "register a tool with a probe");
const cst_tool_def_t *mt = cst_tool_find("app_no_service");
char why[160] = "";
CHECK(mt && cst_tool_available(mt, why, sizeof(why)) != 0,
"the probe says it cannot run");
CHECK(strstr(why, "desktop service") != NULL, "and passes its reason on");
CHECK(mt && !cst_tool_active(cst_agent_config(a), mt),
"so it stays out of tools[] and the prompt");
snprintf(call.name, sizeof(call.name), "app_no_service");
cst_tool_run(&ctx, &call, &res);
CHECK(res.out && strstr(res.out, "cannot run here") != NULL,
"asking for it anyway is answered with the reason");
CHECK(ctx_runs == 1, "and its callback never ran");
cst_tool_result_free(&res);
/* 3. the app can drop its tools again */
CHECK(cst_tool_unregister_owner("app:selftest") == 2, "unregister both");
CHECK(cst_tool_find("app_ping") == NULL, "app_ping is gone");
CHECK(cst_tool_find("read_file") != NULL, "the built-ins are untouched");
cst_agent_destroy(a);
{
char cmd[1200];
snprintf(cmd, sizeof(cmd), "rm -rf %s", ws);
if (system(cmd) != 0)
fprintf(stderr, "note: could not clean %s\n", ws);
}
if (failures) {
fprintf(stderr, "cst-app-selftest: %d failure(s)\n", failures);
return 1;
}
printf("cst-app-selftest: OK\n");
return 0;
}