external_bridge.cpp

src/facade/external_bridge.cpp

@file external_bridge.cpp @brief Unix socket MCP bridge implementation.

Owners: @tvanfossen

ExternalBridge

entropic::ExternalBridge::ExternalBridge(entropic_handle_t handle, const ExternalMCPConfig &config, const std::filesystem::path &project_dir)

Construct with engine handle and config.

src/facade/external_bridge.cpp:1410

Show on the map →

Called by StartedBridgeFixture, start_external_bridge

Calls compute_socket_path, config

Source · 9 lines
ExternalBridge::ExternalBridge(
    entropic_handle_t handle,
    const ExternalMCPConfig& config,
    const std::filesystem::path& project_dir)
    : handle_(handle), config_(config) {
    socket_path_ = config.socket_path.has_value()
        ? config.socket_path.value()
        : compute_socket_path(project_dir);
}
Activity · 1 steps
lines 1415–1417socket_path_ = config.socket_path.has_value() ? config.socket_path.value() : compute_socket_path(project_dir);

Requirements

REQ-BRIDGE-001

accept_loop

void entropic::ExternalBridge::accept_loop()

Background thread: accept connections and serve.

src/facade/external_bridge.cpp:1748

Source · 45 lines
void ExternalBridge::accept_loop() {
    while (running_.load()) {
        struct pollfd pfd{};
        pfd.fd = listen_fd_;
        pfd.events = POLLIN;

        int rc = poll(&pfd, 1, 500);  // 500ms timeout for shutdown check
        if (rc <= 0) { continue; }

        int client_fd = accept(listen_fd_, nullptr, nullptr);
        if (client_fd < 0) { continue; }

        if (!peer_uid_matches(client_fd)) {
            ::close(client_fd);  // v2.1.7 (gh#34): cross-uid attempt
            continue;
        }

        logger->info("External MCP client connected (fd={})", client_fd);

        auto ct = std::make_unique<ClientThread>();
        ct->fd = client_fd;
        // Capture a raw pointer for the thread body so the unique_ptr
        // can stay in client_threads_ without aliasing.
        ClientThread* raw = ct.get();
        // gh#59 (v2.3.1): propagate the handle log scope into the
        // per-client thread so its `serve_client` logs route to the
        // owning handle's session.log.
        int log_id = handle_ ? handle_->log_id : 0;
        ct->thread = std::thread([this, raw, log_id]() {
            entropic::log::HandleLogScope scope(log_id);
            serve_client(raw->fd);
            {
                std::lock_guard<std::mutex> fd_lock(raw->fd_mutex);
                ::close(raw->fd);
                raw->fd = -1;
            }
            logger->info("External MCP client disconnected");
            raw->finished.store(true);
        });

        std::lock_guard<std::mutex> lock(client_threads_mutex_);
        client_threads_.push_back(std::move(ct));
        reap_finished_clients_locked();
    }
}
Activity · 22 steps
lines 1749–1749◇ while (running_.load())lines 1750–1750struct pollfd pfd{};lines 1751–1751pfd.fd = listen_fd_;lines 1752–1752pfd.events = POLLIN;lines 1754–1754int rc = poll(&pfd, 1, 500);lines 1755–1755◇ if (rc <= 0)lines 1755–1755continue;lines 1757–1757int client_fd = accept(listen_fd_, nullptr, nullptr);lines 1758–1758◇ if (client_fd < 0)lines 1758–1758continue;lines 1760–1760◇ if (!peer_uid_matches(client_fd))lines 1761–1761::close(client_fd);lines 1762–1762continue;lines 1765–1765logger->info("External MCP client connected (fd={})", client_fd);lines 1767–1767auto ct = std::make_unique<ClientThread>();lines 1768–1768ct->fd = client_fd;lines 1771–1771ClientThread* raw = ct.get();lines 1775–1775int log_id = handle_ ? handle_->log_id : 0;lines 1776–1786ct->thread = std::thread([this, raw, log_id]() { entropic::log::HandleLogScope scope(log_id); serve_client(raw->fd); { std::lock_guard<std::mutex> fd_lock(raw->fd_mutex); ::close(raw->fd); raw->fd = -1; } logger->info("External MCP client disconnected"); raw->finished.store(true); });lines 1788–1788std::lock_guard<std::mutex> lock(client_threads_mutex_);lines 1789–1789client_threads_.push_back(std::move(ct));lines 1790–1790reap_finished_clients_locked();

Requirements

REQ-BRIDGE-001

Flows

any_cancelling_left

static bool entropic::any_cancelling_left(ExternalBridge *bridge, const std::string &session_key)

True while one session's task is still phase=cancelling.

src/facade/external_bridge.cpp:745

Show on the map →

Called by cancel_inflight_async_tasks

Calls tasks_for_cancel

Source · 10 lines
static bool any_cancelling_left(ExternalBridge* bridge,
                                const std::string& session_key) {
    std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);
    bool left = false;
    for (auto& [_, task] : bridge->tasks_for_cancel()) {
        left = left || (task.session_key == session_key
                        && task.phase == "cancelling");
    }
    return left;
}
Activity · 5 steps
lines 747–747std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);lines 748–748bool left = false;lines 749–749◇ for (auto& [_, task] : bridge->tasks_for_cancel())lines 750–751left = left || (task.session_key == session_key && task.phase == "cancelling");lines 753–753return left;

Requirements

REQ-BRIDGE-001

ask_in_turn

static json entropic::ask_in_turn(entropic_handle_t handle, ExternalBridge *bridge, const json &args, const std::string &session_key, int client_fd, const json &progress_token)

Run a sync ask once this session's turn comes up (gh#144, gh#205).

src/facade/external_bridge.cpp:1064

Show on the map →

Called by dispatch_ask

Calls ask_streaming, handle_ask, handle_ask_plain, held, turn_timeout_result, waited_ms

Source · 11 lines
static json ask_in_turn(entropic_handle_t handle, ExternalBridge* bridge,
                        const json& args, const std::string& session_key,
                        int client_fd, const json& progress_token) {
    TurnTicket ticket(bridge, session_key);
    if (!ticket.held()) {
        return turn_timeout_result(bridge, ticket.waited_ms());
    }
    return bridge->ask_streaming()
        ? handle_ask(handle, args, session_key, client_fd, progress_token)
        : handle_ask_plain(handle, args, session_key);
}
Activity · 4 steps
lines 1067–1067TurnTicket ticket(bridge, session_key);lines 1068–1068◇ if (!ticket.held())lines 1069–1069return turn_timeout_result(bridge, ticket.waited_ms());lines 1071–1073return bridge->ask_streaming() ? handle_ask(handle, args, session_key, client_fd, progress_token) : handle_ask_plain(handle, args, session_key);

Requirements

REQ-BRIDGE-001

async_sentinel_dir

std::filesystem::path entropic::ExternalBridge::async_sentinel_dir() const

Sentinel directory (lazy: returns empty path until the engine's log_dir is configured).

src/facade/external_bridge.cpp:2366

Show on the map →

Called by SCENARIO, TEST_CASE, cleanup_expired_tasks, write_sentinel

Calls none

Source · 7 lines
std::filesystem::path ExternalBridge::async_sentinel_dir() const {
    std::filesystem::path root = async_sentinel_root_override_;
    if (root.empty() && handle_ != nullptr) {
        root = handle_->config.log_dir;
    }
    return root.empty() ? std::filesystem::path{} : (root / "async");
}
Activity · 4 steps
lines 2367–2367std::filesystem::path root = async_sentinel_root_override_;lines 2368–2368◇ if (root.empty() && handle_ != nullptr)lines 2369–2369root = handle_->config.log_dir;lines 2371–2371return root.empty() ? std::filesystem::path{} : (root / "async");

Requirements

REQ-BRIDGE-001

async_worker

void entropic::ExternalBridge::async_worker(const std::string &prompt, const std::string &task_id, int client_fd, const std::string &session_key, const std::string &tier)

Body of one async ask: wait, run, record, notify the owner.

src/facade/external_bridge.cpp:2168

Show on the map →

Called by run_async_ask

Calls attach_phase_observer, begin_turn_wait, cleanup_expired_tasks, commit_async_final_state, derive_async_final_state, detach_phase_observer, end_turn_wait, fail_task_engine_busy, notify_client, run_plain_turn, task_complete_notification, update_task_phase

Source · 26 lines
void ExternalBridge::async_worker(const std::string& prompt,
                                  const std::string& task_id, int client_fd,
                                  const std::string& session_key,
                                  const std::string& tier) {
    long waited_ms = 0;
    if (!begin_turn_wait(kTurnWaitTimeoutMs, &waited_ms, session_key)) {
        fail_task_engine_busy(task_id, waited_ms);
        return;
    }
    update_task_phase(task_id, "running", "running");
    attach_phase_observer(task_id);
    char* result_json = nullptr;
    auto err = run_plain_turn(handle_, session_key, tier, prompt,
                              &result_json);
    detach_phase_observer();
    end_turn_wait(session_key);

    auto final_state = derive_async_final_state(handle_, err, result_json,
                                                prompt, session_key);
    commit_async_final_state(task_id, final_state.status,
                             final_state.phase, final_state.text);
    notify_client(client_fd,
                  task_complete_notification(task_id, final_state.status));
    cleanup_expired_tasks();
    logger->info("Async task {} completed: {}", task_id, final_state.status);
}
Activity · 15 steps
lines 2172–2172long waited_ms = 0;lines 2173–2173◇ if (!begin_turn_wait(kTurnWaitTimeoutMs, &waited_ms, session_key))lines 2174–2174fail_task_engine_busy(task_id, waited_ms);lines 2175–2175return;lines 2177–2177update_task_phase(task_id, "running", "running");lines 2178–2178attach_phase_observer(task_id);lines 2179–2179char* result_json = nullptr;lines 2180–2181auto err = run_plain_turn(handle_, session_key, tier, prompt, &result_json);lines 2182–2182detach_phase_observer();lines 2183–2183end_turn_wait(session_key);lines 2185–2186auto final_state = derive_async_final_state(handle_, err, result_json, prompt, session_key);lines 2187–2188commit_async_final_state(task_id, final_state.status, final_state.phase, final_state.text);lines 2189–2190notify_client(client_fd, task_complete_notification(task_id, final_state.status));lines 2191–2191cleanup_expired_tasks();lines 2192–2192logger->info("Async task {} completed: {}", task_id, final_state.status);

Requirements

REQ-BRIDGE-001

attach_phase_observer

void entropic::ExternalBridge::attach_phase_observer(const std::string &task_id)

Run an async entropic.ask in a background thread.

src/facade/external_bridge.cpp:1944

Show on the map →

Called by SCENARIO, async_worker

Calls entropic_set_state_observer, phase_observer_cb

Source · 8 lines
void ExternalBridge::attach_phase_observer(const std::string& task_id) {
    {
        std::lock_guard<std::mutex> lock(tasks_mutex_);
        active_task_id_ = task_id;
        attached_gen_ = ++observer_gen_;
    }
    entropic_set_state_observer(handle_, phase_observer_cb, this);
}
Activity · 4 steps
lines 1946–1946std::lock_guard<std::mutex> lock(tasks_mutex_);lines 1947–1947active_task_id_ = task_id;lines 1948–1948attached_gen_ = ++observer_gen_;lines 1950–1950entropic_set_state_observer(handle_, phase_observer_cb, this);

Requirements

REQ-BRIDGE-001

begin_turn_wait

bool entropic::ExternalBridge::begin_turn_wait(long timeout_ms, long *waited_ms_out, const std::string &session_key="")

Take a ticket and wait for this caller's turn on the engine.

src/facade/external_bridge.cpp:1302

Show on the map →

Called by SCENARIO, TurnTicket, async_worker

Calls lane_for

Source · 32 lines
bool ExternalBridge::begin_turn_wait(long timeout_ms, long* waited_ms_out,
                                     const std::string& session_key) {
    const auto t0 = std::chrono::steady_clock::now();
    const std::string key = lane_for(session_key);
    std::unique_lock<std::mutex> lock(turn_mutex_);
    TurnLane& lane = lanes_[key];  // map nodes are stable across inserts
    const uint64_t ticket = lane.next_ticket++;
    const bool first = (ticket == lane.now_serving);
    if (!first) { ++lane.waiters; }

    const bool ours = turn_cv_.wait_for(
        lock, std::chrono::milliseconds(timeout_ms),
        [&] { return lane.now_serving == ticket; });

    if (!first) { --lane.waiters; }
    if (waited_ms_out != nullptr) {
        *waited_ms_out = static_cast<long>(
            std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::steady_clock::now() - t0).count());
    }
    if (!ours) {
        // Timed out. Record the ticket as abandoned so that when the line
        // reaches it, it is skipped rather than waited on forever. Do NOT
        // advance now_serving_ here: it currently names ANOTHER caller's
        // in-flight turn, and stepping over it would hand the engine to two
        // callers at once — the exact race this queue exists to prevent.
        lane.abandoned.insert(ticket);
        return false;
    }
    lane.busy = true;
    return true;
}
Activity · 18 steps
lines 1304–1304const auto t0 = std::chrono::steady_clock::now();lines 1305–1305const std::string key = lane_for(session_key);lines 1306–1306std::unique_lock<std::mutex> lock(turn_mutex_);lines 1307–1307TurnLane& lane = lanes_[key];lines 1308–1308const uint64_t ticket = lane.next_ticket++;lines 1309–1309const bool first = (ticket == lane.now_serving);lines 1310–1310◇ if (!first)lines 1310–1310++lane.waiters;lines 1312–1314const bool ours = turn_cv_.wait_for( lock, std::chrono::milliseconds(timeout_ms), [&] { return lane.now_serving == ticket; });lines 1316–1316◇ if (!first)lines 1316–1316--lane.waiters;lines 1317–1317◇ if (waited_ms_out != nullptr)lines 1318–1320*waited_ms_out = static_cast<long>( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - t0).count());lines 1322–1322◇ if (!ours)lines 1328–1328lane.abandoned.insert(ticket);lines 1329–1329return false;lines 1331–1331lane.busy = true;lines 1332–1332return true;

Requirements

REQ-BRIDGE-001

bind_and_listen

static bool entropic::bind_and_listen(int fd, const std::filesystem::path &path)

Bind+listen on an AF_UNIX socket, applying 0600 perms.

src/facade/external_bridge.cpp:1483

Source · 15 lines
static bool bind_and_listen(int fd, const std::filesystem::path& path) {
    auto s = path.string();
    if (s.size() >= sizeof(sockaddr_un::sun_path)) { return false; }
    struct sockaddr_un addr{};
    addr.sun_family = AF_UNIX;
    std::strncpy(addr.sun_path, s.c_str(),
                 sizeof(addr.sun_path) - 1);
    if (bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
        return false;
    }
    ::chmod(s.c_str(), S_IRUSR | S_IWUSR);  // 0600 — owner only
    // v2.14.0: several clients may connect at once; a backlog of 1 refused
    // the second while the accept loop was busy with the first.
    return listen(fd, SOMAXCONN) == 0;
}
Activity · 10 steps
lines 1484–1484auto s = path.string();lines 1485–1485◇ if (s.size() >= sizeof(sockaddr_un::sun_path))lines 1485–1485return false;lines 1486–1486struct sockaddr_un addr{};lines 1487–1487addr.sun_family = AF_UNIX;lines 1488–1489std::strncpy(addr.sun_path, s.c_str(), sizeof(addr.sun_path) - 1);lines 1490–1490◇ if (bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0)lines 1491–1491return false;lines 1493–1493::chmod(s.c_str(), S_IRUSR | S_IWUSR);lines 1496–1496return listen(fd, SOMAXCONN) == 0;

Requirements

REQ-BRIDGE-001

bind_session_workspace

static std::string entropic::bind_session_workspace(entropic_handle_t handle, const std::string &session_key, const std::string &workspace)

Bind a session to the requested workspace, idempotently (gh#205).

src/facade/external_bridge.cpp:1029

Show on the map →

Called by dispatch_ask

Calls bound_workspace, entropic_last_error, entropic_session_bind_workspace, resolve_workspace

Source · 17 lines
static std::string bind_session_workspace(entropic_handle_t handle,
                                          const std::string& session_key,
                                          const std::string& workspace) {
    std::string err;
    if (workspace.empty()) { return err; }
    const std::string name = resolve_workspace(handle, workspace, err);
    const std::string current = err.empty()
        ? bound_workspace(handle, session_key) : std::string{};
    if (err.empty() && current != name) {
        if (entropic_session_bind_workspace(handle, session_key.c_str(),
                                            name.c_str()) != ENTROPIC_OK) {
            const char* msg = entropic_last_error(handle);
            err = msg ? msg : "workspace bind failed";
        }
    }
    return err;
}
Activity · 10 steps
lines 1032–1032std::string err;lines 1033–1033◇ if (workspace.empty())lines 1033–1033return err;lines 1034–1034const std::string name = resolve_workspace(handle, workspace, err);lines 1035–1036const std::string current = err.empty() ? bound_workspace(handle, session_key) : std::string{};lines 1037–1037◇ if (err.empty() && current != name)lines 1038–1039◇ if (entropic_session_bind_workspace(handle, session_key.c_str(), name.c_str()) != ENTROPIC_OK)lines 1040–1040const char* msg = entropic_last_error(handle);lines 1041–1041err = msg ? msg : "workspace bind failed";lines 1044–1044return err;

Requirements

REQ-BRIDGE-001

broadcast_notification

void entropic::ExternalBridge::broadcast_notification(const nlohmann::json &notif)

Write a JSON-RPC notification to every subscribed fd.

src/facade/external_bridge.cpp:2294

Show on the map →

Called by SCENARIO, TEST_CASE

Calls send_nonblocking

Source · 7 lines
void ExternalBridge::broadcast_notification(const json& notif) {
    const auto payload = notif.dump() + "\n";
    std::lock_guard<std::mutex> lock(subscribers_mutex_);
    for (auto it = subscribers_.begin(); it != subscribers_.end();) {
        it = send_nonblocking(*it, payload) ? std::next(it) : subscribers_.erase(it);
    }
}
Activity · 4 steps
lines 2295–2295const auto payload = notif.dump() + "\n";lines 2296–2296std::lock_guard<std::mutex> lock(subscribers_mutex_);lines 2297–2297◇ for (auto it = subscribers_.begin(); it != subscribers_.end();)lines 2298–2298it = send_nonblocking(*it, payload) ? std::next(it) : subscribers_.erase(it);

Requirements

REQ-BRIDGE-001

cancel_inflight_async_tasks

static void entropic::cancel_inflight_async_tasks(entropic_handle_t handle, ExternalBridge *bridge, const std::string &session_key)

Cancel any async tasks currently running on the bridge.

src/facade/external_bridge.cpp:772

Source · 13 lines
static void cancel_inflight_async_tasks(
    entropic_handle_t handle, ExternalBridge* bridge,
    const std::string& session_key) {
    if (bridge == nullptr) { return; }
    // v2.14.0: THIS session's run only. entropic_interrupt is handle-wide —
    // clearing session A used to cancel session B's turn.
    entropic_interrupt_session(handle, session_key.c_str());
    if (!mark_tasks_cancelling(bridge, session_key)) { return; }
    for (int i = 0; i < 20 && any_cancelling_left(bridge, session_key); ++i) {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
    bridge->detach_phase_observer();  // bump gen; silences any stale observer
}
Activity · 8 steps
lines 775–775◇ if (bridge == nullptr)lines 775–775return;lines 778–778entropic_interrupt_session(handle, session_key.c_str());lines 779–779◇ if (!mark_tasks_cancelling(bridge, session_key))lines 779–779return;lines 780–780◇ for (int i = 0; i < 20 && any_cancelling_left(bridge, session_key); ++i)lines 781–781std::this_thread::sleep_for(std::chrono::milliseconds(50));lines 783–783bridge->detach_phase_observer();

Requirements

REQ-BRIDGE-001

cleanup_expired_tasks

void entropic::ExternalBridge::cleanup_expired_tasks()

Remove tasks older than TTL from the registry.

src/facade/external_bridge.cpp:2332

Source · 21 lines
void ExternalBridge::cleanup_expired_tasks() {
    auto cutoff = std::chrono::steady_clock::now()
        - std::chrono::minutes(15);
    auto sentinel_dir = async_sentinel_dir();
    std::lock_guard<std::mutex> lock(tasks_mutex_);
    for (auto it = tasks_.begin(); it != tasks_.end(); ) {
        if (it->second.created < cutoff) {
            if (!sentinel_dir.empty()) {
                for (const char* suffix :
                     {".done", ".failed", ".cancelled"}) {
                    std::error_code ec;
                    std::filesystem::remove(
                        sentinel_dir / (it->first + suffix), ec);
                }
            }
            it = tasks_.erase(it);
        } else {
            ++it;
        }
    }
}
Activity · 12 steps
lines 2333–2334auto cutoff = std::chrono::steady_clock::now() - std::chrono::minutes(15);lines 2335–2335auto sentinel_dir = async_sentinel_dir();lines 2336–2336std::lock_guard<std::mutex> lock(tasks_mutex_);lines 2337–2337◇ for (auto it = tasks_.begin(); it != tasks_.end(); )lines 2338–2338◇ if (it->second.created < cutoff)lines 2339–2339◇ if (!sentinel_dir.empty())lines 2340–2340◇ for (const char* suffix :lines 2342–2342std::error_code ec;lines 2343–2344std::filesystem::remove( sentinel_dir / (it->first + suffix), ec);lines 2347–2347it = tasks_.erase(it);lines 2348–2348elselines 2349–2349++it;

Requirements

REQ-BRIDGE-001

create_listen_socket

static int entropic::create_listen_socket(const std::filesystem::path &path)

Create, bind, and listen on a unix domain socket.

src/facade/external_bridge.cpp:1514

Source · 17 lines
static int create_listen_socket(const std::filesystem::path& path) {
    prepare_socket_dir(path.parent_path());
    if (!socket_path_safe(path)) { return -1; }
    std::filesystem::remove(path);

    int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    bool ok = (fd >= 0) && bind_and_listen(fd, path);
    if (!ok) {
        logger->error("Socket setup failed for {}: {}",
                      path.string(), std::strerror(errno));
        if (fd >= 0) { ::close(fd); }
        return -1;
    }
    // v2.14.0: the old line labelled ~/.entropic as "project_dir(canonical)".
    logger->info("External MCP bridge ready: socket={}", path.string());
    return fd;
}
Activity · 13 steps
lines 1515–1515prepare_socket_dir(path.parent_path());lines 1516–1516◇ if (!socket_path_safe(path))lines 1516–1516return -1;lines 1517–1517std::filesystem::remove(path);lines 1519–1519int fd = socket(AF_UNIX, SOCK_STREAM, 0);lines 1520–1520bool ok = (fd >= 0) && bind_and_listen(fd, path);lines 1521–1521◇ if (!ok)lines 1522–1523logger->error("Socket setup failed for {}: {}", path.string(), std::strerror(errno));lines 1524–1524◇ if (fd >= 0)lines 1524–1524::close(fd);lines 1525–1525return -1;lines 1528–1528logger->info("External MCP bridge ready: socket={}", path.string());lines 1529–1529return fd;

Requirements

REQ-BRIDGE-001

derive_async_final_state

static AsyncFinalState entropic::derive_async_final_state(entropic_handle_t handle, entropic_error_t err, char *result_json, const std::string &prompt, const std::string &session_key)

Translate entropic_run's return code into a final task state.

src/facade/external_bridge.cpp:682

Source · 30 lines
static AsyncFinalState derive_async_final_state(
    entropic_handle_t handle,
    entropic_error_t err,
    char* result_json,
    const std::string& prompt,
    const std::string& session_key) {
    AsyncFinalState s{"error", "failed", ""};
    const char* msg = entropic_last_error(handle);
    if (err == ENTROPIC_ERROR_CANCELLED
        || err == ENTROPIC_ERROR_INTERRUPTED) {
        s = {"cancelled", "cancelled", msg ? msg : "cancelled"};
    } else if (err == ENTROPIC_ERROR_TURN_FAILED) {
        // gh#209/#212 (v2.14.5): the turn ran and the engine failed it.
        // last_error carries the reason and any unconfirmed text.
        s.text = std::string("error: turn failed — ") + (msg ? msg : "unknown");
    } else if (err != ENTROPIC_OK) {
        s.text = msg ? msg : "unknown error";
    } else {
        // gh#130 (v2.10.2): same selection rule as the sync paths. This one
        // had no fallback at all, so a stalled async ask reported
        // status="done" with empty text — even less diagnosable than the
        // sync path's "(no response)". gh#209: bounded to this turn.
        const auto names = session_tool_names(handle, session_key);
        s = {"done", "done",
             facade_text::final_text_or_reason(result_json, prompt.c_str(),
                                               &names)};
    }
    entropic_free(result_json);
    return s;
}
Activity · 15 steps
lines 688–688AsyncFinalState s{"error", "failed", ""};lines 689–689const char* msg = entropic_last_error(handle);lines 690–691◇ if (err == ENTROPIC_ERROR_CANCELLED || err == ENTROPIC_ERROR_INTERRUPTED)lines 692–692s = {"cancelled", "cancelled", msg ? msg : "cancelled"};lines 693–693elselines 693–693◇ if (err == ENTROPIC_ERROR_TURN_FAILED)lines 696–696s.text = std::string("error: turn failed — ") + (msg ? msg : "unknown");lines 697–697elselines 697–697◇ if (err != ENTROPIC_OK)lines 698–698s.text = msg ? msg : "unknown error";lines 699–699elselines 704–704const auto names = session_tool_names(handle, session_key);lines 705–707s = {"done", "done", facade_text::final_text_or_reason(result_json, prompt.c_str(), &names)};lines 709–709entropic_free(result_json);lines 710–710return s;

Requirements

REQ-BRIDGE-001

detach_phase_observer

void entropic::ExternalBridge::detach_phase_observer()

Clear the phase observer installed by attach_phase_observer.

src/facade/external_bridge.cpp:1965

Source · 8 lines
void ExternalBridge::detach_phase_observer() {
    {
        std::lock_guard<std::mutex> lock(tasks_mutex_);
        ++observer_gen_;
        active_task_id_.clear();
    }
    entropic_set_state_observer(handle_, nullptr, nullptr);
}
Activity · 4 steps
lines 1967–1967std::lock_guard<std::mutex> lock(tasks_mutex_);lines 1968–1968++observer_gen_;lines 1969–1969active_task_id_.clear();lines 1971–1971entropic_set_state_observer(handle_, nullptr, nullptr);

Requirements

REQ-BRIDGE-001

dispatch

std::string entropic::ExternalBridge::dispatch(const std::string &request, int client_fd)

Dispatch one JSON-RPC request and return the response.

src/facade/external_bridge.cpp:1883

Show on the map →

Called by SCENARIO, ask, call, call_release, handle_post, stream_call

Calls dispatch_tool, initialize_result, rpc_err, rpc_ok, tool_definitions

Source · 26 lines
std::string ExternalBridge::dispatch(
    const std::string& request, int client_fd) {
    auto req = json::parse(request, nullptr, false);
    // Parse error or notification (no id) → no dispatch
    if (req.is_discarded() || !req.contains("id")) {
        return req.is_discarded()
            ? rpc_err(nullptr, -32700, "Parse error")
            : std::string{};
    }

    json id = req["id"];
    std::string method = req.value("method", std::string{});
    json params = req.value("params", json::object());
    json result;

    if      (method == "initialize")  { result = initialize_result(config_); }
    else if (method == "tools/list")  { result = {{"tools", tool_definitions(config_)}}; }
    else if (method == "tools/call")  {
        auto id_str = id.is_string() ? id.get<std::string>()
                                     : id.dump();
        result = dispatch_tool(handle_, this, params, client_fd, id_str);
    }
    else if (method == "shutdown" || method == "exit") { result = json::object(); }
    else { return rpc_err(id, -32601, "Unknown method: " + method); }
    return rpc_ok(id, result);
}
Activity · 22 steps
lines 1885–1885auto req = json::parse(request, nullptr, false);lines 1887–1887◇ if (req.is_discarded() || !req.contains("id"))lines 1888–1890return req.is_discarded() ? rpc_err(nullptr, -32700, "Parse error") : std::string{};lines 1893–1893json id = req["id"];lines 1894–1894std::string method = req.value("method", std::string{});lines 1895–1895json params = req.value("params", json::object());lines 1896–1896json result;lines 1898–1898◇ if (method == "initialize")lines 1898–1898result = initialize_result(config_);lines 1899–1899elselines 1899–1899◇ if (method == "tools/list")lines 1899–1899result = {{"tools", tool_definitions(config_)}};lines 1900–1900elselines 1900–1900◇ if (method == "tools/call")lines 1901–1902auto id_str = id.is_string() ? id.get<std::string>() : id.dump();lines 1903–1903result = dispatch_tool(handle_, this, params, client_fd, id_str);lines 1905–1905elselines 1905–1905◇ if (method == "shutdown" || method == "exit")lines 1905–1905result = json::object();lines 1906–1906elselines 1906–1906return rpc_err(id, -32601, "Unknown method: " + method);lines 1907–1907return rpc_ok(id, result);

Requirements

REQ-BRIDGE-001

dispatch_ask

static json entropic::dispatch_ask(entropic_handle_t handle, ExternalBridge *bridge, const json &args, int client_fd, const json &progress_token)

Route entropic.ask — sync (streaming) or async.

src/facade/external_bridge.cpp:1087

Source · 29 lines
static json dispatch_ask(entropic_handle_t handle,
                         ExternalBridge* bridge,
                         const json& args,
                         int client_fd,
                         const json& progress_token) {
    // gh#144 (v2.12.0): optional. Absent means the shared default session,
    // i.e. exactly what every pre-2.12.0 client already gets.
    const std::string session_key = args.value("session", std::string{});
    // gh#205 (v2.14.0): bind the session to its repository before it runs.
    const std::string ws_err = bind_session_workspace(
        handle, session_key, args.value("workspace", std::string{}));
    json result;
    if (!ws_err.empty()) {
        result = tool_text("error: " + ws_err);
    } else if (args.value("async", false)) {
        // The async worker takes its own ticket inside run_async_ask — it
        // must not hold one here, or registering the task would block behind
        // an in-flight turn and defeat the point of async.
        auto task_id = generate_task_id();
        bridge->run_async_ask(
            args.value("prompt", ""), task_id, client_fd, session_key,
            args.value("tier", std::string{}));
        result = tool_text("async task started: " + task_id);
    } else {
        result = ask_in_turn(handle, bridge, args, session_key, client_fd,
                             progress_token);
    }
    return result;
}
Activity · 13 steps
lines 1094–1094const std::string session_key = args.value("session", std::string{});lines 1096–1097const std::string ws_err = bind_session_workspace( handle, session_key, args.value("workspace", std::string{}));lines 1098–1098json result;lines 1099–1099◇ if (!ws_err.empty())lines 1100–1100result = tool_text("error: " + ws_err);lines 1101–1101elselines 1101–1101◇ if (args.value("async", false))lines 1105–1105auto task_id = generate_task_id();lines 1106–1108bridge->run_async_ask( args.value("prompt", ""), task_id, client_fd, session_key, args.value("tier", std::string{}));lines 1109–1109result = tool_text("async task started: " + task_id);lines 1110–1110elselines 1111–1112result = ask_in_turn(handle, bridge, args, session_key, client_fd, progress_token);lines 1114–1114return result;

Requirements

REQ-BRIDGE-001

dispatch_tool

static json entropic::dispatch_tool(entropic_handle_t handle, ExternalBridge *bridge, const json &params, int client_fd, const std::string &call_id)

Dispatch a tools/call to the appropriate handler.

src/facade/external_bridge.cpp:1263

Source · 28 lines
static json dispatch_tool(entropic_handle_t handle,
                          ExternalBridge* bridge,
                          const json& params,
                          int client_fd,
                          const std::string& call_id) {
    std::string name = params.value("name", std::string{});
    json args = params.value("arguments", json::object());
    // gh#145: strip the configured namespace, then match bare suffixes
    // against the same table tool_definitions() advertised from.
    const std::string suffix =
        facade::strip_tool_prefix(
            bridge->config().tool_prefix, name);
    if (suffix == tool_suffix::kAsk) {
        // v2.14.0: the client's own _meta.progressToken when it sent one
        // (MCP), else the request id so pre-2.14.0 clients keep streaming.
        json token = call_id;
        if (params.contains("_meta") && params["_meta"].is_object()
            && params["_meta"].contains("progressToken")) {
            token = params["_meta"]["progressToken"];
        }
        return dispatch_ask(handle, bridge, args, client_fd, token);
    }
    const auto& handlers = tool_handlers();
    const auto it = handlers.find(suffix);
    return it == handlers.end()
        ? tool_text("error: unknown tool '" + name + "'")
        : it->second(handle, bridge, args);
}
Activity · 11 steps
lines 1268–1268std::string name = params.value("name", std::string{});lines 1269–1269json args = params.value("arguments", json::object());lines 1272–1274const std::string suffix = facade::strip_tool_prefix( bridge->config().tool_prefix, name);lines 1275–1275◇ if (suffix == tool_suffix::kAsk)lines 1278–1278json token = call_id;lines 1279–1280◇ if (params.contains("_meta") && params["_meta"].is_object() && params["_meta"].contains("progressToken"))lines 1281–1281token = params["_meta"]["progressToken"];lines 1283–1283return dispatch_ask(handle, bridge, args, client_fd, token);lines 1285–1285const auto& handlers = tool_handlers();lines 1286–1286const auto it = handlers.find(suffix);lines 1287–1289return it == handlers.end() ? tool_text("error: unknown tool '" + name + "'") : it->second(handle, bridge, args);

Requirements

REQ-BRIDGE-001

end_turn_wait

void entropic::ExternalBridge::end_turn_wait(const std::string &session_key="")

Hand the turn to the next ticket in this session's lane.

src/facade/external_bridge.cpp:1340

Show on the map →

Called by SCENARIO, async_worker, ~TurnTicket

Calls lane_for

Source · 19 lines
void ExternalBridge::end_turn_wait(const std::string& session_key) {
    {
        std::lock_guard<std::mutex> lock(turn_mutex_);
        auto it = lanes_.find(lane_for(session_key));
        if (it != lanes_.end()) {
            TurnLane& lane = it->second;
            lane.busy = false;
            ++lane.now_serving;
            // Step over anyone who gave up while waiting, or the line stalls
            // on a ticket whose owner is long gone.
            while (lane.abandoned.erase(lane.now_serving) > 0) {
                ++lane.now_serving;
            }
            // An idle lane holds nothing worth keeping.
            if (lane.now_serving == lane.next_ticket) { lanes_.erase(it); }
        }
    }
    turn_cv_.notify_all();
}
Activity · 11 steps
lines 1342–1342std::lock_guard<std::mutex> lock(turn_mutex_);lines 1343–1343auto it = lanes_.find(lane_for(session_key));lines 1344–1344◇ if (it != lanes_.end())lines 1345–1345TurnLane& lane = it->second;lines 1346–1346lane.busy = false;lines 1347–1347++lane.now_serving;lines 1350–1350◇ while (lane.abandoned.erase(lane.now_serving) > 0)lines 1351–1351++lane.now_serving;lines 1354–1354◇ if (lane.now_serving == lane.next_ticket)lines 1354–1354lanes_.erase(it);lines 1357–1357turn_cv_.notify_all();

Requirements

REQ-BRIDGE-001

final_answer_from_context

static json entropic::final_answer_from_context(entropic_handle_t handle, const std::string &session_key, entropic_error_t err, const std::string &prompt)

Read the live conversation and render the operator-visible answer.

src/facade/external_bridge.cpp:445

Source · 10 lines
static json final_answer_from_context(entropic_handle_t handle,
                                      const std::string& session_key,
                                      entropic_error_t err,
                                      const std::string& prompt) {
    char* msgs_json = nullptr;
    entropic_session_context_get(handle, session_key.c_str(), &msgs_json);
    auto result = render_turn(handle, session_key, err, msgs_json, prompt);
    entropic_free(msgs_json);
    return result;
}
Activity · 5 steps
lines 449–449char* msgs_json = nullptr;lines 450–450entropic_session_context_get(handle, session_key.c_str(), &msgs_json);lines 451–451auto result = render_turn(handle, session_key, err, msgs_json, prompt);lines 452–452entropic_free(msgs_json);lines 453–453return result;

Requirements

REQ-API-012 REQ-BRIDGE-001

handle_ask

static json entropic::handle_ask(entropic_handle_t handle, const json &args, const std::string &session_key, int client_fd, const json &progress_token)

Handle entropic.ask — stream tokens then return final text.

src/facade/external_bridge.cpp:558

Show on the map →

Called by ask_in_turn

Calls entropic_last_error, final_answer_from_context, on_token, run_stream_turn, send_progress, tool_error, tool_text

Source · 26 lines
static json handle_ask(entropic_handle_t handle, const json& args,
                       const std::string& session_key,
                       int client_fd, const json& progress_token) {
    auto it = args.find("prompt");
    if (it == args.end() || !it->is_string()) {
        return tool_text("error: missing 'prompt' argument");
    }
    std::string prompt = it->get<std::string>();

    // Stream tokens as progress notifications
    struct StreamCtx { int fd; json token; uint64_t seq; };
    StreamCtx sctx{client_fd, progress_token, 0};
    auto on_token = [](const char* tok, size_t len, void* ud) {
        auto* ctx = static_cast<StreamCtx*>(ud);
        send_progress(ctx->fd, std::string(tok, len), ctx->token, ++ctx->seq);
    };
    // gh#205: a requested tier locks the turn; absent routes as before.
    auto err = run_stream_turn(handle, session_key,
                               args.value("tier", std::string{}), prompt,
                               on_token, &sctx);
    if (err != ENTROPIC_OK && err != ENTROPIC_ERROR_TURN_FAILED) {
        const char* msg = entropic_last_error(handle);
        return tool_error(std::string("error: ") + (msg ? msg : "unknown"));
    }
    return final_answer_from_context(handle, session_key, err, prompt);
}
Activity · 12 steps
lines 561–561auto it = args.find("prompt");lines 562–562◇ if (it == args.end() || !it->is_string())lines 563–563return tool_text("error: missing 'prompt' argument");lines 565–565std::string prompt = it->get<std::string>();lines 568–568struct StreamCtx { int fd; json token; uint64_t seq; }lines 569–569StreamCtx sctx{client_fd, progress_token, 0};lines 570–573auto on_token = [](const char* tok, size_t len, void* ud) { auto* ctx = static_cast<StreamCtx*>(ud); send_progress(ctx->fd, std::string(tok, len), ctx->token, ++ctx->seq); };lines 575–577auto err = run_stream_turn(handle, session_key, args.value("tier", std::string{}), prompt, on_token, &sctx);lines 578–578◇ if (err != ENTROPIC_OK && err != ENTROPIC_ERROR_TURN_FAILED)lines 579–579const char* msg = entropic_last_error(handle);lines 580–580return tool_error(std::string("error: ") + (msg ? msg : "unknown"));lines 582–582return final_answer_from_context(handle, session_key, err, prompt);

Requirements

REQ-API-012 REQ-BRIDGE-001

handle_ask_plain

static json entropic::handle_ask_plain(entropic_handle_t handle, const json &args, const std::string &session_key)

Handle entropic.ask — non-streaming path (gh#115, v2.9.12).

src/facade/external_bridge.cpp:518

Show on the map →

Called by ask_in_turn

Calls entropic_free, entropic_free, entropic_last_error, render_turn, run_plain_turn, tool_error, tool_text

Source · 22 lines
static json handle_ask_plain(entropic_handle_t handle, const json& args,
                             const std::string& session_key) {
    auto it = args.find("prompt");
    if (it == args.end() || !it->is_string()) {
        return tool_text("error: missing 'prompt' argument");
    }
    char* result_json = nullptr;
    const auto prompt = it->get<std::string>();
    auto err = run_plain_turn(handle, session_key,
                              args.value("tier", std::string{}),  // gh#205
                              prompt, &result_json);
    json out;
    if (err == ENTROPIC_OK || err == ENTROPIC_ERROR_TURN_FAILED) {
        // Resolve before the free — render_turn reads that buffer.
        out = render_turn(handle, session_key, err, result_json, prompt);
    } else {
        const char* msg = entropic_last_error(handle);
        out = tool_error(std::string("error: ") + (msg ? msg : "unknown"));
    }
    entropic_free(result_json);
    return out;
}
Activity · 14 steps
lines 520–520auto it = args.find("prompt");lines 521–521◇ if (it == args.end() || !it->is_string())lines 522–522return tool_text("error: missing 'prompt' argument");lines 524–524char* result_json = nullptr;lines 525–525const auto prompt = it->get<std::string>();lines 526–528auto err = run_plain_turn(handle, session_key, args.value("tier", std::string{}), // gh#205 prompt, &result_json);lines 529–529json out;lines 530–530◇ if (err == ENTROPIC_OK || err == ENTROPIC_ERROR_TURN_FAILED)lines 532–532out = render_turn(handle, session_key, err, result_json, prompt);lines 533–533elselines 534–534const char* msg = entropic_last_error(handle);lines 535–535out = tool_error(std::string("error: ") + (msg ? msg : "unknown"));lines 537–537entropic_free(result_json);lines 538–538return out;

Requirements

REQ-API-012 REQ-BRIDGE-001

handle_ask_status

json entropic::ExternalBridge::handle_ask_status(const nlohmann::json &args)

Handle entropic.ask_status — check async task state.

src/facade/external_bridge.cpp:843

Show on the map →

Called by SCENARIO, TEST_CASE, tool_handlers

Calls tool_text

Source · 15 lines
json ExternalBridge::handle_ask_status(const json& args) {
    auto tid = args.value("task_id", std::string{});
    std::lock_guard<std::mutex> lock(tasks_mutex_);
    auto it = tasks_.find(tid);
    if (it == tasks_.end()) {
        return tool_text("error: unknown task_id");
    }
    json status = {{"status", it->second.status},
                   {"phase",  it->second.phase}};
    if (!it->second.result.empty()) {
        auto key = (it->second.status == "error") ? "error" : "result";
        status[key] = it->second.result;
    }
    return tool_text(status.dump());
}
Activity · 10 steps
lines 844–844auto tid = args.value("task_id", std::string{});lines 845–845std::lock_guard<std::mutex> lock(tasks_mutex_);lines 846–846auto it = tasks_.find(tid);lines 847–847◇ if (it == tasks_.end())lines 848–848return tool_text("error: unknown task_id");lines 850–851json status = {{"status", it->second.status}, {"phase", it->second.phase}};lines 852–852◇ if (!it->second.result.empty())lines 853–853auto key = (it->second.status == "error") ? "error" : "result";lines 854–854status[key] = it->second.result;lines 856–856return tool_text(status.dump());

Requirements

REQ-BRIDGE-001

handle_clear

static json entropic::handle_clear(entropic_handle_t handle, ExternalBridge *bridge, const std::string &session_key)

entropic.context_clear MCP tool handler.

src/facade/external_bridge.cpp:798

Source · 16 lines
static json handle_clear(entropic_handle_t handle,
                         ExternalBridge* bridge,
                         const std::string& session_key) {
    cancel_inflight_async_tasks(handle, bridge, session_key);
    // gh#144 (v2.12.0): clear ONLY the named session. The unscoped clear
    // wiped every caller's context, which the issue correctly observed "is
    // not isolation" — with two callers active there is no ordering in which
    // it is correct.
    auto err = entropic_session_context_clear(handle, session_key.c_str());
    if (err != ENTROPIC_OK) {
        return tool_text("error: clear failed");
    }
    return tool_text(session_key.empty()
        ? "conversation cleared"
        : "conversation cleared for session '" + session_key + "'");
}
Activity · 5 steps
lines 801–801cancel_inflight_async_tasks(handle, bridge, session_key);lines 806–806auto err = entropic_session_context_clear(handle, session_key.c_str());lines 807–807◇ if (err != ENTROPIC_OK)lines 808–808return tool_text("error: clear failed");lines 810–812return tool_text(session_key.empty() ? "conversation cleared" : "conversation cleared for session '" + session_key + "'");

Requirements

REQ-BRIDGE-001

handle_count

static json entropic::handle_count(entropic_handle_t handle, const std::string &session_key)

Handle entropic.context_count .

src/facade/external_bridge.cpp:822

Source · 7 lines
static json handle_count(entropic_handle_t handle,
                         const std::string& session_key) {
    size_t count = 0;
    // gh#144 (v2.12.0): count only the named session.
    entropic_session_context_count(handle, session_key.c_str(), &count);
    return tool_text(std::to_string(count));
}
Activity · 3 steps
lines 824–824size_t count = 0;lines 826–826entropic_session_context_count(handle, session_key.c_str(), &count);lines 827–827return tool_text(std::to_string(count));

Requirements

REQ-BRIDGE-001

handle_release

static json entropic::handle_release(entropic_handle_t handle)

release : unload every resident model, keep everything else.

src/facade/external_bridge.cpp:1155

Source · 21 lines
static json handle_release(entropic_handle_t handle) {
    const std::string before = resident_tiers(handle);
    const entropic_error_t rc = entropic_release_model(handle, nullptr);
    json result;
    if (rc == ENTROPIC_ERROR_ALREADY_RUNNING) {
        result = tool_text("error: a turn is running on this engine; nothing "
                           "was released — retry when it finishes");
        result["isError"] = true;
    } else if (rc != ENTROPIC_OK) {
        const char* why = entropic_last_error(handle);
        result = tool_text(std::string("error: release failed: ")
                           + (why != nullptr ? why : "unknown"));
        result["isError"] = true;
    } else {
        result = tool_text(before.empty()
            ? "released: nothing was resident"
            : "released: " + before + " — sessions kept; the next ask reloads");
    }
    logger->info("[release] rc={} resident_before='{}'", static_cast<int>(rc), before);
    return result;
}
Activity · 15 steps
lines 1156–1156const std::string before = resident_tiers(handle);lines 1157–1157const entropic_error_t rc = entropic_release_model(handle, nullptr);lines 1158–1158json result;lines 1159–1159◇ if (rc == ENTROPIC_ERROR_ALREADY_RUNNING)lines 1160–1161result = tool_text("error: a turn is running on this engine; nothing " "was released — retry when it finishes");lines 1162–1162result["isError"] = true;lines 1163–1163elselines 1163–1163◇ if (rc != ENTROPIC_OK)lines 1164–1164const char* why = entropic_last_error(handle);lines 1165–1166result = tool_text(std::string("error: release failed: ") + (why != nullptr ? why : "unknown"));lines 1167–1167result["isError"] = true;lines 1168–1168elselines 1169–1171result = tool_text(before.empty() ? "released: nothing was resident" : "released: " + before + " — sessions kept; the next ask reloads");lines 1173–1173logger->info("[release] rc={} resident_before='{}'", static_cast<int>(rc), before);lines 1174–1174return result;

Requirements

REQ-BRIDGE-001 REQ-INFER-019

handle_shutdown

static json entropic::handle_shutdown(entropic_handle_t handle, ExternalBridge *bridge)

Handle .shutdown : stop the host over MCP (v2.14.6).

src/facade/external_bridge.cpp:1195

Show on the map →

Called by tool_handlers

Calls config, tool_error, tool_text

Source · 19 lines
static json handle_shutdown(entropic_handle_t handle, ExternalBridge* bridge) {
    if (!bridge->config().allow_shutdown) {
        return tool_text("error: unknown tool 'shutdown'");
    }
    const bool claimed = handle->engine == nullptr
        || handle->engine->try_begin_turn("__shutdown__", /*exclusive=*/true);
    if (!claimed) {
        return tool_error("error: a turn is running on this engine; not "
                          "stopping — retry when it finishes");
    }
    logger->warn("[shutdown] accepted over MCP — stopping the host");
    std::thread([] {
        // Let the reply reach the client before teardown closes the listener.
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
        ::kill(::getpid(), SIGTERM);
    }).detach();
    return tool_text("stopping: the host is shutting down — models unloaded, "
                     "sessions ended, token removed");
}
Activity · 8 steps
lines 1196–1196◇ if (!bridge->config().allow_shutdown)lines 1197–1197return tool_text("error: unknown tool 'shutdown'");lines 1199–1200const bool claimed = handle->engine == nullptr || handle->engine->try_begin_turn("__shutdown__", /*exclusive=*/true);lines 1201–1201◇ if (!claimed)lines 1202–1203return tool_error("error: a turn is running on this engine; not " "stopping — retry when it finishes");lines 1205–1205logger->warn("[shutdown] accepted over MCP — stopping the host");lines 1206–1210std::thread([] { // Let the reply reach the client before teardown closes the listener. std::this_thread::sleep_for(std::chrono::milliseconds(250)); ::kill(::getpid(), SIGTERM); }).detach();lines 1211–1212return tool_text("stopping: the host is shutting down — models unloaded, " "sessions ended, token removed");

Requirements

REQ-BRIDGE-001

handle_status

static json entropic::handle_status(entropic_handle_t handle, const ExternalBridge *bridge)

Handle the status tool.

src/facade/external_bridge.cpp:604

Show on the map →

Called by tool_handlers

Calls entropic_context_count, entropic_free, entropic_free, entropic_metrics_json, entropic_session_list, entropic_version, tool_text, turn_in_flight, turn_queue_depth

Source · 26 lines
static json handle_status(entropic_handle_t handle,
                          const ExternalBridge* bridge) {
    size_t count = 0;
    entropic_context_count(handle, &count);
    std::ostringstream os;
    os << "entropic " << entropic_version()
       << "\nmessages: " << count
       << "\nbusy: " << (bridge->turn_in_flight() ? "true" : "false")
       << "\nqueue_depth: " << bridge->turn_queue_depth();
    // gh#144 (v2.12.0): which callers this host is serving, and how much
    // history each holds.
    char* sessions = nullptr;
    if (entropic_session_list(handle, &sessions) == ENTROPIC_OK
        && sessions != nullptr) {
        os << "\nsessions: " << sessions;
        entropic_free(sessions);
    }
    // Metrics + per-tier breakdown (P2-15 follow-up, 2.0.6-rc16.2)
    char* mjson = nullptr;
    if (entropic_metrics_json(handle, &mjson) == ENTROPIC_OK
        && mjson != nullptr) {
        os << "\nmetrics: " << mjson;
        entropic_free(mjson);
    }
    return tool_text(os.str());
}
Activity · 13 steps
lines 606–606size_t count = 0;lines 607–607entropic_context_count(handle, &count);lines 608–608std::ostringstream os;lines 609–612os << "entropic " << entropic_version() << "\nmessages: " << count << "\nbusy: " << (bridge->turn_in_flight() ? "true" : "false") << "\nqueue_depth: " << bridge->turn_queue_depth();lines 615–615char* sessions = nullptr;lines 616–617◇ if (entropic_session_list(handle, &sessions) == ENTROPIC_OK && sessions != nullptr)lines 618–618os << "\nsessions: " << sessions;lines 619–619entropic_free(sessions);lines 622–622char* mjson = nullptr;lines 623–624◇ if (entropic_metrics_json(handle, &mjson) == ENTROPIC_OK && mjson != nullptr)lines 625–625os << "\nmetrics: " << mjson;lines 626–626entropic_free(mjson);lines 628–628return tool_text(os.str());

Requirements

REQ-BRIDGE-001

initialize_result

static json entropic::initialize_result(const ExternalMCPConfig &cfg)

Build the MCP initialize response payload.

src/facade/external_bridge.cpp:1859

Source · 10 lines
static json initialize_result(const ExternalMCPConfig& cfg) {
    const std::string name =
        cfg.server_name.empty() ? "entropic" : cfg.server_name;
    return {
        {"protocolVersion", "2025-06-18"},
        {"serverInfo", {{"name", name},
                        {"version", entropic_version()}}},
        {"capabilities", {{"tools", json::object()}}}
    };
}
Activity · 2 steps
lines 1860–1861const std::string name = cfg.server_name.empty() ? "entropic" : cfg.server_name;lines 1862–1867return { {"protocolVersion", "2025-06-18"}, {"serverInfo", {{"name", name}, {"version", entropic_version()}}}, {"capabilities", {{"tools", json::object()}}} };

Requirements

REQ-BRIDGE-001

mark_tasks_cancelling

static bool entropic::mark_tasks_cancelling(ExternalBridge *bridge, const std::string &session_key)

Mark one session's queued/running tasks as cancelling.

src/facade/external_bridge.cpp:721

Show on the map →

Called by cancel_inflight_async_tasks

Calls tasks_for_cancel

Source · 15 lines
static bool mark_tasks_cancelling(ExternalBridge* bridge,
                                  const std::string& session_key) {
    std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);
    bool any = false;
    for (auto& [_, task] : bridge->tasks_for_cancel()) {
        // v2.14.0: only the cleared session's tasks.
        if (task.session_key != session_key) { continue; }
        if (task.status == "queued" || task.status == "running") {
            task.status = "cancelled";
            task.phase = "cancelling";
            any = true;
        }
    }
    return any;
}
Activity · 10 steps
lines 723–723std::lock_guard<std::mutex> lock(bridge->tasks_mutex_);lines 724–724bool any = false;lines 725–725◇ for (auto& [_, task] : bridge->tasks_for_cancel())lines 727–727◇ if (task.session_key != session_key)lines 727–727continue;lines 728–728◇ if (task.status == "queued" || task.status == "running")lines 729–729task.status = "cancelled";lines 730–730task.phase = "cancelling";lines 731–731any = true;lines 734–734return any;

Requirements

REQ-BRIDGE-001

peer_uid_matches

static bool entropic::peer_uid_matches(int client_fd)

Validate that the connecting peer shares the engine's UID.

src/facade/external_bridge.cpp:1546

Show on the map →

Called by accept_loop

Calls none

Source · 17 lines
static bool peer_uid_matches(int client_fd) {
    struct ucred cred{};
    socklen_t len = sizeof(cred);
    if (getsockopt(client_fd, SOL_SOCKET, SO_PEERCRED,
                   &cred, &len) != 0) {
        logger->warn("SO_PEERCRED failed on fd={}: {}",
                     client_fd, std::strerror(errno));
        return false;
    }
    if (cred.uid != ::geteuid()) {
        logger->warn(
            "Rejecting MCP client on fd={}: peer uid {} != engine uid {}",
            client_fd, cred.uid, ::geteuid());
        return false;
    }
    return true;
}
Activity · 9 steps
lines 1547–1547struct ucred cred{};lines 1548–1548socklen_t len = sizeof(cred);lines 1549–1550◇ if (getsockopt(client_fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0)lines 1551–1552logger->warn("SO_PEERCRED failed on fd={}: {}", client_fd, std::strerror(errno));lines 1553–1553return false;lines 1555–1555◇ if (cred.uid != ::geteuid())lines 1556–1558logger->warn( "Rejecting MCP client on fd={}: peer uid {} != engine uid {}", client_fd, cred.uid, ::geteuid());lines 1559–1559return false;lines 1561–1561return true;

Requirements

REQ-BRIDGE-001

Flows

prepare_socket_dir

static void entropic::prepare_socket_dir(const std::filesystem::path &parent)

Prepare the socket containing directory with 0700 perms.

src/facade/external_bridge.cpp:1440

Source · 5 lines
static void prepare_socket_dir(const std::filesystem::path& parent) {
    std::error_code ec;
    std::filesystem::create_directories(parent, ec);
    ::chmod(parent.c_str(), S_IRWXU);  // 0700
}
Activity · 3 steps
lines 1441–1441std::error_code ec;lines 1442–1442std::filesystem::create_directories(parent, ec);lines 1443–1443::chmod(parent.c_str(), S_IRWXU);

Requirements

REQ-BRIDGE-001

reap_finished_clients_locked

void entropic::ExternalBridge::reap_finished_clients_locked()

Reap finished client threads from client_threads_.

src/facade/external_bridge.cpp:1711

Show on the map →

Called by accept_loop

Calls none

Source · 11 lines
void ExternalBridge::reap_finished_clients_locked() {
    auto it = client_threads_.begin();
    while (it != client_threads_.end()) {
        if ((*it)->finished.load()) {
            if ((*it)->thread.joinable()) { (*it)->thread.join(); }
            it = client_threads_.erase(it);
        } else {
            ++it;
        }
    }
}
Activity · 8 steps
lines 1712–1712auto it = client_threads_.begin();lines 1713–1713◇ while (it != client_threads_.end())lines 1714–1714◇ if ((*it)->finished.load())lines 1715–1715◇ if ((*it)->thread.joinable())lines 1715–1715(*it)->thread.join();lines 1716–1716it = client_threads_.erase(it);lines 1717–1717elselines 1718–1718++it;

Flows

render_turn

static json entropic::render_turn(entropic_handle_t handle, const std::string &session_key, entropic_error_t err, const char *convo, const std::string &prompt)

Render a finished turn as the ask tool result.

src/facade/external_bridge.cpp:413

Source · 12 lines
static json render_turn(entropic_handle_t handle, const std::string& session_key,
                        entropic_error_t err, const char* convo,
                        const std::string& prompt) {
    if (err == ENTROPIC_ERROR_TURN_FAILED) {
        const char* msg = entropic_last_error(handle);
        return tool_error(std::string("error: turn failed — ")
                          + (msg ? msg : "unknown"));
    }
    const auto names = session_tool_names(handle, session_key);
    return tool_text(
        facade_text::final_text_or_reason(convo, prompt.c_str(), &names));
}
Activity · 5 steps
lines 416–416◇ if (err == ENTROPIC_ERROR_TURN_FAILED)lines 417–417const char* msg = entropic_last_error(handle);lines 418–419return tool_error(std::string("error: turn failed — ") + (msg ? msg : "unknown"));lines 421–421const auto names = session_tool_names(handle, session_key);lines 422–423return tool_text( facade_text::final_text_or_reason(convo, prompt.c_str(), &names));

Requirements

REQ-API-012 REQ-BRIDGE-001

run_async_ask

void entropic::ExternalBridge::run_async_ask(const std::string &prompt, const std::string &task_id, int client_fd, const std::string &session_key="", const std::string &tier="")

Run an ask on a background worker and notify its owner.

src/facade/external_bridge.cpp:2074

Show on the map →

Called by SCENARIO, TEST_CASE, dispatch_ask

Calls async_worker, reap_finished_async_locked

Source · 34 lines
void ExternalBridge::run_async_ask(
    const std::string& prompt,
    const std::string& task_id,
    int client_fd,
    const std::string& session_key,
    const std::string& tier) {
    {
        std::lock_guard<std::mutex> lock(tasks_mutex_);
        AsyncTask t;
        t.status = "queued";
        t.phase = "queued";
        t.created = std::chrono::steady_clock::now();
        t.session_key = session_key;  // v2.14.0: clear cancels per session
        t.owner_fd = client_fd;       // v2.14.0: only the owner is notified
        tasks_[task_id] = std::move(t);
    }

    // gh#59 (v2.3.1): the async-ask worker runs entropic_run on this
    // handle's behalf — scope its logs to the owning handle.
    int log_id = handle_ ? handle_->log_id : 0;
    // v2.14.2: owned and joined by stop(), no longer detached — a detached
    // worker outliving the bridge touched freed memory (TSan).
    auto worker = std::make_unique<AsyncWorker>();
    AsyncWorker* raw = worker.get();
    std::lock_guard<std::mutex> lock(async_workers_mutex_);
    reap_finished_async_locked();
    worker->thread = std::thread([this, raw, prompt, task_id, client_fd,
                                  log_id, session_key, tier]() {
        entropic::log::HandleLogScope scope(log_id);
        async_worker(prompt, task_id, client_fd, session_key, tier);
        raw->finished.store(true);
    });
    async_workers_.push_back(std::move(worker));
}
Activity · 15 steps
lines 2081–2081std::lock_guard<std::mutex> lock(tasks_mutex_);lines 2082–2082AsyncTask t;lines 2083–2083t.status = "queued";lines 2084–2084t.phase = "queued";lines 2085–2085t.created = std::chrono::steady_clock::now();lines 2086–2086t.session_key = session_key;lines 2087–2087t.owner_fd = client_fd;lines 2088–2088tasks_[task_id] = std::move(t);lines 2093–2093int log_id = handle_ ? handle_->log_id : 0;lines 2096–2096auto worker = std::make_unique<AsyncWorker>();lines 2097–2097AsyncWorker* raw = worker.get();lines 2098–2098std::lock_guard<std::mutex> lock(async_workers_mutex_);lines 2099–2099reap_finished_async_locked();lines 2100–2105worker->thread = std::thread([this, raw, prompt, task_id, client_fd, log_id, session_key, tier]() { entropic::log::HandleLogScope scope(log_id); async_worker(prompt, task_id, client_fd, session_key, tier); raw->finished.store(true); });lines 2106–2106async_workers_.push_back(std::move(worker));

Requirements

REQ-BRIDGE-001

sentinel_suffix_for_status

static const char * entropic::sentinel_suffix_for_status(const std::string &status)

Map a terminal status string to a sentinel filename suffix.

src/facade/external_bridge.cpp:2390

Source · 10 lines
static const char* sentinel_suffix_for_status(
    const std::string& status) {
    const char* suffix = ".done";
    if (status == "error") {
        suffix = ".failed";
    } else if (status == "cancelled") {
        suffix = ".cancelled";
    }
    return suffix;
}
Activity · 7 steps
lines 2392–2392const char* suffix = ".done";lines 2393–2393◇ if (status == "error")lines 2394–2394suffix = ".failed";lines 2395–2395elselines 2395–2395◇ if (status == "cancelled")lines 2396–2396suffix = ".cancelled";lines 2398–2398return suffix;

Requirements

REQ-BRIDGE-001

serve_client

void entropic::ExternalBridge::serve_client(int client_fd)

Serve a single connected client until disconnect.

src/facade/external_bridge.cpp:1822

Source · 21 lines
void ExternalBridge::serve_client(int client_fd) {
    subscribe(client_fd);
    struct Unsub {
        ExternalBridge* self;
        int fd;
        ~Unsub() { self->unsubscribe(fd); }
    } guard{this, client_fd};

    while (running_.load()) {
        auto line = read_line(client_fd);
        if (line.empty()) { break; }

        auto response = dispatch(line, client_fd);
        if (response.empty()) { continue; }  // notification — no reply
        response += '\n';

        ssize_t written = write(client_fd, response.c_str(),
                                response.size());
        if (written < 0) { break; }
    }
}
Activity · 13 steps
lines 1823–1823subscribe(client_fd);lines 1824–1828struct Unsub { ExternalBridge* self; int fd; ~Unsub() { self->unsubscribe(fd); } } guard{this, client_fd};lines 1830–1830◇ while (running_.load())lines 1831–1831auto line = read_line(client_fd);lines 1832–1832◇ if (line.empty())lines 1832–1832break;lines 1834–1834auto response = dispatch(line, client_fd);lines 1835–1835◇ if (response.empty())lines 1835–1835continue;lines 1836–1836response += '\n';lines 1838–1839ssize_t written = write(client_fd, response.c_str(), response.size());lines 1840–1840◇ if (written < 0)lines 1840–1840break;

Requirements

REQ-BRIDGE-001

Flows

session_tool_names

static facade_text::ToolNames entropic::session_tool_names(entropic_handle_t handle, const std::string &session_key)

The tool names a session's turns can see (gh#212 bare-name rule).

src/facade/external_bridge.cpp:385

Source · 6 lines
static facade_text::ToolNames session_tool_names(entropic_handle_t handle,
                                                 const std::string& session_key) {
    auto* servers = entropic::workspace_servers(handle, session_key);
    return servers != nullptr ? facade_text::tool_names_of(servers->list_tools())
                              : facade_text::ToolNames{};
}
Activity · 2 steps
lines 387–387auto* servers = entropic::workspace_servers(handle, session_key);lines 388–389return servers != nullptr ? facade_text::tool_names_of(servers->list_tools()) : facade_text::ToolNames{};

Requirements

REQ-BRIDGE-001

set_async_sentinel_root

void entropic::ExternalBridge::set_async_sentinel_root(const std::filesystem::path &root)

Override the async sentinel root directory.

src/facade/external_bridge.cpp:2379

Show on the map →

Called by SCENARIO, TEST_CASE

Calls none

Source · 4 lines
void ExternalBridge::set_async_sentinel_root(
    const std::filesystem::path& root) {
    async_sentinel_root_override_ = root;
}
Activity · 1 steps
lines 2381–2381async_sentinel_root_override_ = root;

Requirements

REQ-BRIDGE-001

socket_path_safe

static bool entropic::socket_path_safe(const std::filesystem::path &path)

Reject a pre-existing path that is a symlink or non-socket.

src/facade/external_bridge.cpp:1459

Source · 15 lines
static bool socket_path_safe(const std::filesystem::path& path) {
    struct stat st{};
    if (::lstat(path.c_str(), &st) != 0) {
        return errno == ENOENT;  // absent is fine
    }
    bool is_symlink = S_ISLNK(st.st_mode);
    bool is_socket = S_ISSOCK(st.st_mode);
    if (!is_socket || is_symlink) {
        logger->error(
            "Refusing to bind: {} is a {} (expected unix socket)",
            path.string(),
            is_symlink ? "symlink" : "non-socket file");
    }
    return is_socket && !is_symlink;
}
Activity · 8 steps
lines 1460–1460struct stat st{};lines 1461–1461◇ if (::lstat(path.c_str(), &st) != 0)lines 1462–1462return errno == ENOENT;lines 1464–1464bool is_symlink = S_ISLNK(st.st_mode);lines 1465–1465bool is_socket = S_ISSOCK(st.st_mode);lines 1466–1466◇ if (!is_socket || is_symlink)lines 1467–1470logger->error( "Refusing to bind: {} is a {} (expected unix socket)", path.string(), is_symlink ? "symlink" : "non-socket file");lines 1472–1472return is_socket && !is_symlink;

Requirements

REQ-BRIDGE-001

start

bool entropic::ExternalBridge::start()

Start the background accept loop.

src/facade/external_bridge.cpp:1570

Source · 55 lines
bool ExternalBridge::start() {
    // v2.14.0: a key that bounds nothing must say so rather than look like
    // a control (cf. gh#175).
    if (config_.rate_limit != ExternalMCPConfig{}.rate_limit) {
        logger->warn("mcp.external.rate_limit={} is not enforced and is "
                     "ignored", config_.rate_limit);
    }
    // Refuse to start if another handle in this process already owns
    // this socket path. The pre-fix create_listen_socket call unlinks
    // any existing socket file before binding — that's correct for
    // crashed-prior-process recovery, but if a live in-process bridge
    // owned that file, the unlink stole its binding silently. The
    // claim must happen *before* create_listen_socket so a concurrent
    // start() on a colliding path cannot pass the check and then race
    // into the unlink.
    std::error_code ec;
    auto canonical =
        std::filesystem::weakly_canonical(socket_path_, ec).string();
    if (ec) { canonical = socket_path_.string(); }
    {
        std::lock_guard lk(s_bound_sockets_mu);
        if (!s_bound_sockets.insert(canonical).second) {
            logger->warn(
                "External MCP bridge: socket {} already bound by another "
                "handle in this process; declining to start. Set "
                "external.socket_path to a distinct path per handle "
                "if you need per-handle bridges.",
                canonical);
            return false;
        }
    }

    listen_fd_ = create_listen_socket(socket_path_);
    if (listen_fd_ < 0) {
        std::lock_guard lk(s_bound_sockets_mu);
        s_bound_sockets.erase(canonical);
        return false;
    }
    bound_canonical_ = canonical;

    running_.store(true);
    // gh#59 (v2.3.1): the accept thread (and the per-client serve
    // threads it spawns) need to log on this handle's behalf — install
    // a HandleLogScope at the top of each thread body so spdlog lines
    // route through HandleAwareSink to this handle's session.log.
    int log_id = handle_ ? handle_->log_id : 0;
    accept_thread_ = std::thread([this, log_id]() {
        entropic::log::HandleLogScope scope(log_id);
        accept_loop();
    });

    logger->info("External MCP bridge listening on {}",
                 socket_path_.string());
    return true;
}
Activity · 21 steps
lines 1573–1573◇ if (config_.rate_limit != ExternalMCPConfig{}.rate_limit)lines 1574–1575logger->warn("mcp.external.rate_limit={} is not enforced and is " "ignored", config_.rate_limit);lines 1585–1585std::error_code ec;lines 1586–1587auto canonical = std::filesystem::weakly_canonical(socket_path_, ec).string();lines 1588–1588◇ if (ec)lines 1588–1588canonical = socket_path_.string();lines 1590–1590std::lock_guard lk(s_bound_sockets_mu);lines 1591–1591◇ if (!s_bound_sockets.insert(canonical).second)lines 1592–1597logger->warn( "External MCP bridge: socket {} already bound by another " "handle in this process; declining to start. Set " "external.socket_path to a distinct path per handle " "if you need per-handle bridges.", canonical);lines 1598–1598return false;lines 1602–1602listen_fd_ = create_listen_socket(socket_path_);lines 1603–1603◇ if (listen_fd_ < 0)lines 1604–1604std::lock_guard lk(s_bound_sockets_mu);lines 1605–1605s_bound_sockets.erase(canonical);lines 1606–1606return false;lines 1608–1608bound_canonical_ = canonical;lines 1610–1610running_.store(true);lines 1615–1615int log_id = handle_ ? handle_->log_id : 0;lines 1616–1619accept_thread_ = std::thread([this, log_id]() { entropic::log::HandleLogScope scope(log_id); accept_loop(); });lines 1621–1622logger->info("External MCP bridge listening on {}", socket_path_.string());lines 1623–1623return true;

Requirements

REQ-BRIDGE-001

stop

void entropic::ExternalBridge::stop()

Stop the accept loop and close the socket.

src/facade/external_bridge.cpp:1646

Show on the map →

Called by SCENARIO, TEST_CASE, entropic_destroy, ~ExternalBridge, ~StartedBridgeFixture

Calls join_async_workers

Source · 52 lines
void ExternalBridge::stop() {
    running_.store(false);
    // v2.14.0: the accept thread READS listen_fd_ every poll, so it must be
    // joined before listen_fd_ is written. shutdown() wakes a blocked
    // poll/accept without touching the variable; the loop then sees
    // running_ == false (it re-checks at least every 500 ms regardless).
    // Closing first was a data race TSan reported the first time a test
    // destroyed a handle with the bridge enabled.
    if (listen_fd_ >= 0) { ::shutdown(listen_fd_, SHUT_RDWR); }
    if (accept_thread_.joinable()) {
        accept_thread_.join();
    }
    if (listen_fd_ >= 0) {
        ::close(listen_fd_);
        listen_fd_ = -1;
    }

    // Wake every connected client's blocking read so the per-client
    // thread can observe the disconnect and exit. shutdown(SHUT_RDWR)
    // on a connected socket returns EOF to the peer; the read in
    // serve_client returns 0 and read_line returns "" → exits.
    std::vector<std::unique_ptr<ClientThread>> drained;
    {
        std::lock_guard<std::mutex> lock(client_threads_mutex_);
        drained = std::move(client_threads_);
        client_threads_.clear();
    }
    for (auto& ct : drained) {
        // v2.14.2: under the client's fd_mutex — its thread may be closing
        // the same descriptor right now (TSan).
        std::lock_guard<std::mutex> fd_lock(ct->fd_mutex);
        if (ct->fd >= 0) { ::shutdown(ct->fd, SHUT_RDWR); }
    }
    for (auto& ct : drained) {
        if (ct->thread.joinable()) { ct->thread.join(); }
    }
    join_async_workers();  // v2.14.2: no worker may outlive the bridge

    // Clean up socket file
    std::error_code ec;
    std::filesystem::remove(socket_path_, ec);

    // Release our claim on the canonical path so a later handle in
    // this process can re-bind. Use the exact string we inserted in
    // start(); recomputing weakly_canonical here could differ if the
    // path was deleted mid-run.
    if (!bound_canonical_.empty()) {
        std::lock_guard lk(s_bound_sockets_mu);
        s_bound_sockets.erase(bound_canonical_);
        bound_canonical_.clear();
    }
}
Activity · 26 steps
lines 1647–1647running_.store(false);lines 1654–1654◇ if (listen_fd_ >= 0)lines 1654–1654::shutdown(listen_fd_, SHUT_RDWR);lines 1655–1655◇ if (accept_thread_.joinable())lines 1656–1656accept_thread_.join();lines 1658–1658◇ if (listen_fd_ >= 0)lines 1659–1659::close(listen_fd_);lines 1660–1660listen_fd_ = -1;lines 1667–1667std::vector<std::unique_ptr<ClientThread>> drained;lines 1669–1669std::lock_guard<std::mutex> lock(client_threads_mutex_);lines 1670–1670drained = std::move(client_threads_);lines 1671–1671client_threads_.clear();lines 1673–1673◇ for (auto& ct : drained)lines 1676–1676std::lock_guard<std::mutex> fd_lock(ct->fd_mutex);lines 1677–1677◇ if (ct->fd >= 0)lines 1677–1677::shutdown(ct->fd, SHUT_RDWR);lines 1679–1679◇ for (auto& ct : drained)lines 1680–1680◇ if (ct->thread.joinable())lines 1680–1680ct->thread.join();lines 1682–1682join_async_workers();lines 1685–1685std::error_code ec;lines 1686–1686std::filesystem::remove(socket_path_, ec);lines 1692–1692◇ if (!bound_canonical_.empty())lines 1693–1693std::lock_guard lk(s_bound_sockets_mu);lines 1694–1694s_bound_sockets.erase(bound_canonical_);lines 1695–1695bound_canonical_.clear();

Requirements

REQ-BRIDGE-001

Flows

subscribe

void entropic::ExternalBridge::subscribe(int fd)

Add a connected fd to the subscriber set.

src/facade/external_bridge.cpp:2206

Show on the map →

Called by SCENARIO, TEST_CASE, serve_client

Calls none

Source · 4 lines
void ExternalBridge::subscribe(int fd) {
    std::lock_guard<std::mutex> lock(subscribers_mutex_);
    subscribers_.insert(fd);
}
Activity · 2 steps
lines 2207–2207std::lock_guard<std::mutex> lock(subscribers_mutex_);lines 2208–2208subscribers_.insert(fd);

Requirements

REQ-BRIDGE-001

Flows

tool_definitions

static json entropic::tool_definitions(const ExternalMCPConfig &cfg)

MCP tool definitions exposed by the bridge.

src/facade/external_bridge.cpp:302

Show on the map →

Called by dispatch

Calls ask_status_tool, ask_tool, no_args_tool, session_scoped_tool

Source · 26 lines
static json tool_definitions(const ExternalMCPConfig& cfg) {
    auto tools = json::array({
        ask_tool(cfg),
        ask_status_tool(cfg),
        no_args_tool(cfg, tool_suffix::kStatus,
                     "Engine version and message count."),
        session_scoped_tool(cfg, tool_suffix::kContextClear,
                            "Clear conversation history."),
        session_scoped_tool(cfg, tool_suffix::kContextCount,
                            "Return the message count."),
        // v2.14.3: the one way an MCP client can give the card back.
        no_args_tool(cfg, tool_suffix::kRelease,
                     "Unload every loaded model to free GPU/host memory. "
                     "Sessions and their conversations are kept; the next "
                     "ask reloads the model. Call when you are done for "
                     "now. Refused while a turn is running — retry then."),
    });
    // v2.14.6: only when the host opted in (entropic serve --allow-shutdown).
    if (cfg.allow_shutdown) {
        tools.push_back(no_args_tool(cfg, tool_suffix::kShutdown,
            "Stop this host process: models are unloaded, every session "
            "ends, the token is removed. Refused while a turn is running — "
            "retry then. Use release instead to only free the GPU."));
    }
    return tools;
}
Activity · 4 steps
lines 303–318auto tools = json::array({ ask_tool(cfg), ask_status_tool(cfg), no_args_tool(cfg, tool_suffix::kStatus, "Engine version and message count."), session_scoped_tool(cfg, tool_suffix::kContextClear, "Clear conversation history."), session_scoped_tool(cfg, tool_suffix::kContextCount, "Return the message count."), // v2.14.3: the one way an MCP client can give the card back. no_args_tool(cfg, tool_suffix::kRelease, "Unload every loaded model to free GPU/host memory. " "Sessions and their conversations are kept; the next " "ask reloads the model. Call when you are done for " "now. Refused while a turn is running — retry then."), });lines 320–320◇ if (cfg.allow_shutdown)lines 321–324tools.push_back(no_args_tool(cfg, tool_suffix::kShutdown, "Stop this host process: models are unloaded, every session " "ends, the token is removed. Refused while a turn is running — " "retry then. Use release instead to only free the GPU."));lines 326–326return tools;

Requirements

REQ-BRIDGE-001

tool_handlers

static const std::unordered_map< std::string, ToolHandler > & entropic::tool_handlers()

Non-ask tools by suffix (v2.14.3).

src/facade/external_bridge.cpp:1229

Source · 17 lines
static const std::unordered_map<std::string, ToolHandler>& tool_handlers() {
    static const std::unordered_map<std::string, ToolHandler> table = {
        {tool_suffix::kAskStatus, [](entropic_handle_t, ExternalBridge* b, const json& a) {
             return b->handle_ask_status(a); }},
        {tool_suffix::kStatus, [](entropic_handle_t h, ExternalBridge* b, const json&) {
             return handle_status(h, b); }},
        {tool_suffix::kContextClear, [](entropic_handle_t h, ExternalBridge* b, const json& a) {
             return handle_clear(h, b, a.value("session", std::string{})); }},
        {tool_suffix::kContextCount, [](entropic_handle_t h, ExternalBridge*, const json& a) {
             return handle_count(h, a.value("session", std::string{})); }},
        {tool_suffix::kRelease, [](entropic_handle_t h, ExternalBridge*, const json&) {
             return handle_release(h); }},
        {tool_suffix::kShutdown, [](entropic_handle_t h, ExternalBridge* b, const json&) {
             return handle_shutdown(h, b); }},
    };
    return table;
}
Activity · 2 steps
lines 1230–1243static const std::unordered_map<std::string, ToolHandler> table = { {tool_suffix::kAskStatus, [](entropic_handle_t, ExternalBridge* b, const json& a) { return b->handle_ask_status(a); }}, {tool_suffix::kStatus, [](entropic_handle_t h, ExternalBridge* b, const json&) { return handle_status(h, b); }}, {tool_suffix::kContextClear, [](entropic_handle_t h, ExternalBridge* b, const json& a) { return handle_clear(h, b, a.value("session", std::string{})); }}, {tool_suffix::kContextCount, [](entropic_handle_t h, ExternalBridge*, const json& a) { return handle_count(h, a.value("session", std::string{})); }}, {tool_suffix::kRelease, [](entropic_handle_t h, ExternalBridge*, const json&) { return handle_release(h); }}, {tool_suffix::kShutdown, [](entropic_handle_t h, ExternalBridge* b, const json&) { return handle_shutdown(h, b); }}, };lines 1244–1244return table;

Requirements

REQ-BRIDGE-001

turn_timeout_result

json entropic::anonymous_namespace{external_bridge.cpp}::turn_timeout_result(const ExternalBridge *bridge, long waited_ms)

The tool result returned when the queue deadline expired.

src/facade/external_bridge.cpp:947

Show on the map →

Called by ask_in_turn

Calls tool_text, turn_queue_depth

Source · 7 lines
json turn_timeout_result(const ExternalBridge* bridge, long waited_ms) {
    std::ostringstream os;
    os << "error: engine busy — waited " << waited_ms << " ms with "
       << bridge->turn_queue_depth() << " request(s) still ahead. "
       << "Another caller's turn is still running; retry shortly.";
    return tool_text(os.str());
}
Activity · 3 steps
lines 948–948std::ostringstream os;lines 949–951os << "error: engine busy — waited " << waited_ms << " ms with " << bridge->turn_queue_depth() << " request(s) still ahead. " << "Another caller's turn is still running; retry shortly.";lines 952–952return tool_text(os.str());

Requirements

REQ-BRIDGE-001

unsubscribe

void entropic::ExternalBridge::unsubscribe(int fd)

Remove an fd from the subscriber set.

src/facade/external_bridge.cpp:2217

Show on the map →

Called by SCENARIO, TEST_CASE

Calls none

Source · 4 lines
void ExternalBridge::unsubscribe(int fd) {
    std::lock_guard<std::mutex> lock(subscribers_mutex_);
    subscribers_.erase(fd);
}
Activity · 2 steps
lines 2218–2218std::lock_guard<std::mutex> lock(subscribers_mutex_);lines 2219–2219subscribers_.erase(fd);

Requirements

REQ-BRIDGE-001

update_task_phase

void entropic::ExternalBridge::update_task_phase(const std::string &task_id, const std::string &status, const std::string &phase)

Update status/phase for a tracked task atomically.

src/facade/external_bridge.cpp:2310

Show on the map →

Called by async_worker, fail_task_engine_busy

Calls none

Source · 9 lines
void ExternalBridge::update_task_phase(const std::string& task_id,
                                       const std::string& status,
                                       const std::string& phase) {
    std::lock_guard<std::mutex> lock(tasks_mutex_);
    auto it = tasks_.find(task_id);
    if (it == tasks_.end()) { return; }
    it->second.status = status;
    it->second.phase = phase;
}
Activity · 6 steps
lines 2313–2313std::lock_guard<std::mutex> lock(tasks_mutex_);lines 2314–2314auto it = tasks_.find(task_id);lines 2315–2315◇ if (it == tasks_.end())lines 2315–2315return;lines 2316–2316it->second.status = status;lines 2317–2317it->second.phase = phase;

Requirements

REQ-BRIDGE-001

write_sentinel

void entropic::ExternalBridge::write_sentinel(const std::string &task_id, const std::string &status)

Write the sentinel file for an async task completion.

src/facade/external_bridge.cpp:2416

Show on the map →

Called by SCENARIO, TEST_CASE, commit_async_final_state, fail_task_engine_busy

Calls async_sentinel_dir, sentinel_suffix_for_status

Source · 19 lines
void ExternalBridge::write_sentinel(const std::string& task_id,
                                    const std::string& status) {
    auto dir = async_sentinel_dir();
    if (dir.empty()) { return; }
    std::error_code ec;
    std::filesystem::create_directories(dir, ec);
    if (ec) {
        logger->warn("write_sentinel: mkdir {} failed: {}",
                     dir.string(), ec.message());
        return;
    }
    auto path = dir / (task_id + sentinel_suffix_for_status(status));
    std::ofstream out(path);
    if (!out.is_open()) {
        logger->warn("write_sentinel: open {} failed", path.string());
        return;
    }
    out << status << '\n';
}
Activity · 14 steps
lines 2418–2418auto dir = async_sentinel_dir();lines 2419–2419◇ if (dir.empty())lines 2419–2419return;lines 2420–2420std::error_code ec;lines 2421–2421std::filesystem::create_directories(dir, ec);lines 2422–2422◇ if (ec)lines 2423–2424logger->warn("write_sentinel: mkdir {} failed: {}", dir.string(), ec.message());lines 2425–2425return;lines 2427–2427auto path = dir / (task_id + sentinel_suffix_for_status(status));lines 2428–2428std::ofstream out(path);lines 2429–2429◇ if (!out.is_open())lines 2430–2430logger->warn("write_sentinel: open {} failed", path.string());lines 2431–2431return;lines 2433–2433out << status << '\n';

Requirements

REQ-BRIDGE-001

~ExternalBridge

entropic::ExternalBridge::~ExternalBridge()

Destructor — stop if running.

src/facade/external_bridge.cpp:1425

Show on the map →

Called by none

Calls stop

The index is older than this file: the lines it records no longer hold this function. Refresh the index to bundle its body.

Requirements

REQ-BRIDGE-001