WIP Telegram: modulo akode-telegram (API e impostazioni), in pausa
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -87,6 +87,7 @@ akode-rmcp-client = { workspace = true }
|
||||
akode-rollout = { workspace = true }
|
||||
akode-sandboxing = { workspace = true }
|
||||
akode-state = { workspace = true }
|
||||
akode-telegram = { workspace = true }
|
||||
akode-thread-store = { workspace = true }
|
||||
akode-tools = { workspace = true }
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
|
||||
@@ -409,6 +409,54 @@ pub async fn start(mut args: InProcessStartArgs) -> IoResult<InProcessClientHand
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// One JSON-RPC message from the in-process Telegram bridge, with the bookkeeping the
|
||||
/// socket transport loop does for its connections.
|
||||
async fn handle_bridge_message(
|
||||
processor: &Arc<MessageProcessor>,
|
||||
session: &Arc<ConnectionSessionState>,
|
||||
message: akode_app_server_protocol::JSONRPCMessage,
|
||||
outbound_initialized: &AtomicBool,
|
||||
outbound_experimental_api_enabled: &AtomicBool,
|
||||
outbound_opted_out_notification_methods: &RwLock<HashSet<String>>,
|
||||
) {
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
let bridge_id = crate::telegram_bridge::IN_PROCESS_BRIDGE_CONNECTION_ID;
|
||||
match message {
|
||||
JSONRPCMessage::Request(request) => {
|
||||
let was_initialized = session.initialized();
|
||||
processor
|
||||
.process_request(
|
||||
bridge_id,
|
||||
request,
|
||||
&crate::transport::AppServerTransport::Off,
|
||||
Arc::clone(session),
|
||||
)
|
||||
.await;
|
||||
if let Ok(mut opted_out) = outbound_opted_out_notification_methods.write() {
|
||||
*opted_out = session.opted_out_notification_methods();
|
||||
}
|
||||
outbound_experimental_api_enabled
|
||||
.store(session.experimental_api_enabled(), Ordering::Release);
|
||||
if !was_initialized && session.initialized() {
|
||||
processor
|
||||
.send_initialize_notifications_to_connection(bridge_id)
|
||||
.await;
|
||||
processor.connection_initialized(bridge_id).await;
|
||||
outbound_initialized.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
JSONRPCMessage::Response(response) => {
|
||||
processor.process_response(bridge_id, response).await;
|
||||
}
|
||||
JSONRPCMessage::Notification(notification) => {
|
||||
processor.process_notification(notification).await;
|
||||
}
|
||||
JSONRPCMessage::Error(error) => {
|
||||
processor.process_error(bridge_id, error).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_outbound_router(
|
||||
mut outgoing_rx: mpsc::Receiver<OutgoingEnvelope>,
|
||||
mut outbound_connections: HashMap<ConnectionId, OutboundConnectionState>,
|
||||
@@ -477,7 +525,57 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
let outbound_experimental_api_enabled = Arc::new(AtomicBool::new(false));
|
||||
let outbound_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new()));
|
||||
|
||||
// The Telegram bridge is a second, internal connection of this app-server.
|
||||
let bridge_id = crate::telegram_bridge::IN_PROCESS_BRIDGE_CONNECTION_ID;
|
||||
let (bridge_writer_tx, mut bridge_writer_rx) =
|
||||
mpsc::channel::<QueuedOutgoingMessage>(channel_capacity);
|
||||
let bridge_initialized = Arc::new(AtomicBool::new(false));
|
||||
let bridge_experimental_api_enabled = Arc::new(AtomicBool::new(false));
|
||||
let bridge_opted_out_notification_methods = Arc::new(RwLock::new(HashSet::new()));
|
||||
let bridge_sink = Arc::new(std::sync::Mutex::new(
|
||||
None::<mpsc::UnboundedSender<akode_app_server_protocol::JSONRPCMessage>>,
|
||||
));
|
||||
let bridge_forward = tokio::spawn({
|
||||
let bridge_sink = Arc::clone(&bridge_sink);
|
||||
async move {
|
||||
while let Some(queued) = bridge_writer_rx.recv().await {
|
||||
let sink = bridge_sink
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
if let Some(sink) = sink
|
||||
&& let Some(message) =
|
||||
crate::telegram_bridge::to_jsonrpc(&queued.message)
|
||||
{
|
||||
let _ = sink.send(message);
|
||||
}
|
||||
if let Some(done) = queued.write_complete_tx {
|
||||
let _ = done.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (bridge_events_tx, mut bridge_events_rx) = mpsc::unbounded_channel();
|
||||
let bridge_shutdown = tokio_util::sync::CancellationToken::new();
|
||||
let bridge_task = (args.session_source == SessionSource::Cli).then(|| {
|
||||
crate::telegram_bridge::spawn_in_process_bridge(
|
||||
args.config.codex_home.to_path_buf(),
|
||||
bridge_events_tx,
|
||||
bridge_shutdown.clone(),
|
||||
)
|
||||
});
|
||||
|
||||
let mut outbound_connections = HashMap::<ConnectionId, OutboundConnectionState>::new();
|
||||
outbound_connections.insert(
|
||||
bridge_id,
|
||||
OutboundConnectionState::new(
|
||||
bridge_writer_tx,
|
||||
Arc::clone(&bridge_initialized),
|
||||
Arc::clone(&bridge_experimental_api_enabled),
|
||||
Arc::clone(&bridge_opted_out_notification_methods),
|
||||
/*disconnect_sender*/ None,
|
||||
),
|
||||
);
|
||||
outbound_connections.insert(
|
||||
IN_PROCESS_CONNECTION_ID,
|
||||
OutboundConnectionState::new(
|
||||
@@ -526,9 +624,51 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
crate::transport::ConnectionOrigin::InProcess,
|
||||
));
|
||||
let mut listen_for_threads = true;
|
||||
let mut bridge_events_open = bridge_task.is_some();
|
||||
let mut bridge_session: Option<Arc<ConnectionSessionState>> = None;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = bridge_events_rx.recv(), if bridge_events_open => {
|
||||
use crate::telegram_bridge::InProcessBridgeEvent;
|
||||
match event {
|
||||
Some(InProcessBridgeEvent::Opened(sink)) => {
|
||||
if let Some(old) = bridge_session.take() {
|
||||
processor.connection_closed(bridge_id, &old).await;
|
||||
}
|
||||
bridge_initialized.store(false, Ordering::Release);
|
||||
*bridge_sink
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(sink);
|
||||
bridge_session = Some(Arc::new(ConnectionSessionState::new(
|
||||
crate::transport::ConnectionOrigin::InProcess,
|
||||
)));
|
||||
}
|
||||
Some(InProcessBridgeEvent::Message(message)) => {
|
||||
if let Some(bridge) = bridge_session.as_ref() {
|
||||
handle_bridge_message(
|
||||
&processor,
|
||||
bridge,
|
||||
message,
|
||||
&bridge_initialized,
|
||||
&bridge_experimental_api_enabled,
|
||||
&bridge_opted_out_notification_methods,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Some(InProcessBridgeEvent::Closed) => {
|
||||
bridge_initialized.store(false, Ordering::Release);
|
||||
*bridge_sink
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
|
||||
if let Some(old) = bridge_session.take() {
|
||||
processor.connection_closed(bridge_id, &old).await;
|
||||
}
|
||||
}
|
||||
None => bridge_events_open = false,
|
||||
}
|
||||
}
|
||||
command = processor_rx.recv() => {
|
||||
match command {
|
||||
Some(ProcessorCommand::Request(request, cancellation)) => {
|
||||
@@ -577,11 +717,17 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
created = thread_created_rx.recv(), if listen_for_threads => {
|
||||
match created {
|
||||
Ok(thread_id) => {
|
||||
let connection_ids = if session.initialized() {
|
||||
let mut connection_ids = if session.initialized() {
|
||||
vec![IN_PROCESS_CONNECTION_ID]
|
||||
} else {
|
||||
Vec::<ConnectionId>::new()
|
||||
};
|
||||
if bridge_session
|
||||
.as_ref()
|
||||
.is_some_and(|bridge| bridge.initialized())
|
||||
{
|
||||
connection_ids.push(bridge_id);
|
||||
}
|
||||
processor
|
||||
.try_attach_thread_listener(thread_id, connection_ids)
|
||||
.await;
|
||||
@@ -597,6 +743,14 @@ async fn start_uninitialized(mut args: InProcessStartArgs) -> IoResult<InProcess
|
||||
}
|
||||
}
|
||||
|
||||
bridge_shutdown.cancel();
|
||||
if let Some(task) = bridge_task {
|
||||
task.abort();
|
||||
}
|
||||
bridge_forward.abort();
|
||||
if let Some(bridge) = bridge_session.take() {
|
||||
processor.connection_closed(bridge_id, &bridge).await;
|
||||
}
|
||||
processor.clear_runtime_references();
|
||||
processor.cancel_active_login().await;
|
||||
processor
|
||||
|
||||
@@ -140,6 +140,7 @@ mod request_processors;
|
||||
mod request_serialization;
|
||||
mod server_request_error;
|
||||
mod skills_watcher;
|
||||
mod telegram_bridge;
|
||||
mod startup_warnings;
|
||||
mod thread_sample;
|
||||
mod thread_state;
|
||||
@@ -812,6 +813,14 @@ pub async fn run_main_with_transport_options(
|
||||
AppServerTransport::Off => {}
|
||||
}
|
||||
drop(unix_socket_startup_lock);
|
||||
// The shared daemon serves every session it hosts to Telegram (when enabled).
|
||||
let _telegram_bridge = matches!(&transport, AppServerTransport::UnixSocket { .. }).then(|| {
|
||||
telegram_bridge::spawn_daemon_bridge(
|
||||
codex_home.to_path_buf(),
|
||||
transport_event_tx.clone(),
|
||||
transport_shutdown_token.clone(),
|
||||
)
|
||||
});
|
||||
|
||||
let remote_control_enabled = remote_control_policy == RemoteControlPolicy::Allowed
|
||||
&& remote_control_explicitly_requested
|
||||
|
||||
@@ -1490,6 +1490,53 @@ mod tests {
|
||||
assert_eq!(result, Err(error));
|
||||
}
|
||||
|
||||
/// The TUI and the Telegram bridge both subscribe to a thread: an approval reaches
|
||||
/// both, the first answer resolves it and a later answer from the other is ignored.
|
||||
#[tokio::test]
|
||||
async fn approval_goes_to_every_subscriber_and_first_answer_wins() {
|
||||
let (tx, mut rx) = mpsc::channel::<OutgoingEnvelope>(8);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(tx));
|
||||
let thread_id = ThreadId::new();
|
||||
let tui = ConnectionId(1);
|
||||
let telegram = ConnectionId(2);
|
||||
let thread_outgoing =
|
||||
ThreadScopedOutgoingMessageSender::new(outgoing.clone(), vec![tui, telegram], thread_id);
|
||||
let (request_id, waiter) = thread_outgoing
|
||||
.send_request(ServerRequestPayload::FileChangeRequestApproval(
|
||||
FileChangeRequestApprovalParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
item_id: "call-1".to_string(),
|
||||
started_at_ms: 0,
|
||||
reason: None,
|
||||
grant_root: None,
|
||||
},
|
||||
))
|
||||
.await;
|
||||
let mut recipients = Vec::new();
|
||||
for _ in 0..2 {
|
||||
match rx.recv().await {
|
||||
Some(OutgoingEnvelope::ToConnection { connection_id, .. }) => {
|
||||
recipients.push(connection_id)
|
||||
}
|
||||
other => panic!("unexpected envelope: {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(recipients, vec![tui, telegram]);
|
||||
|
||||
outgoing
|
||||
.notify_client_response(telegram, request_id.clone(), json!({"decision": "accept"}))
|
||||
.await;
|
||||
outgoing
|
||||
.notify_client_response(tui, request_id, json!({"decision": "decline"}))
|
||||
.await;
|
||||
let result = timeout(Duration::from_secs(1), waiter)
|
||||
.await
|
||||
.expect("answered in time")
|
||||
.expect("callback");
|
||||
assert_eq!(result, Ok(json!({"decision": "accept"})));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_requests_for_thread_returns_thread_requests_in_request_id_order() {
|
||||
let (tx, _rx) = mpsc::channel::<OutgoingEnvelope>(8);
|
||||
|
||||
@@ -15,7 +15,11 @@ use crate::message_processor::ConnectionSessionState;
|
||||
use crate::message_processor::InitializedConnectionSessionState;
|
||||
use crate::transport::ConnectionOrigin;
|
||||
|
||||
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &["akode_app_server_daemon", "codex-backend"];
|
||||
const NON_ORIGINATING_CLIENT_NAMES: &[&str] = &[
|
||||
"akode_app_server_daemon",
|
||||
"codex-backend",
|
||||
akode_telegram::CLIENT_NAME,
|
||||
];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct InitializeRequestProcessor {
|
||||
|
||||
158
akode-rs/app-server/src/telegram_bridge.rs
Normal file
158
akode-rs/app-server/src/telegram_bridge.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
//! Hosts the Telegram bridge ([`akode_telegram`]) as an internal client connection.
|
||||
//!
|
||||
//! The shared daemon starts it for every session it serves; an in-process (`--no-daemon`)
|
||||
//! TUI starts it for its own sessions. Either way the bridge polls Telegram only while
|
||||
//! `[telegram] enabled = true` and while its process holds the poll lock in `AKODE_HOME`,
|
||||
//! so one bot never has two pollers.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use akode_telegram::bridge::BridgeConnection;
|
||||
use akode_telegram::bridge::BridgeOptions;
|
||||
use akode_telegram::bridge::Connector;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::outgoing_message::ConnectionId;
|
||||
use crate::transport::CHANNEL_CAPACITY;
|
||||
use crate::transport::ConnectionOrigin;
|
||||
use crate::transport::OutgoingMessage;
|
||||
use crate::transport::QueuedOutgoingMessage;
|
||||
use crate::transport::TransportEvent;
|
||||
|
||||
/// JSON-RPC form of an outgoing message, as a socket client would read it.
|
||||
pub(crate) fn to_jsonrpc(message: &OutgoingMessage) -> Option<JSONRPCMessage> {
|
||||
match serde_json::to_value(message).and_then(serde_json::from_value) {
|
||||
Ok(message) => Some(message),
|
||||
Err(err) => {
|
||||
warn!("telegram: cannot convert an outgoing message: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drains the connection's writer into the bridge so the server never waits on it.
|
||||
pub(crate) fn forward_writer(
|
||||
mut writer_rx: mpsc::Receiver<QueuedOutgoingMessage>,
|
||||
to_bridge: mpsc::UnboundedSender<JSONRPCMessage>,
|
||||
) -> JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
while let Some(queued) = writer_rx.recv().await {
|
||||
if let Some(message) = to_jsonrpc(&queued.message)
|
||||
&& to_bridge.send(message).is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
if let Some(done) = queued.write_complete_tx {
|
||||
let _ = done.send(());
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the bridge in the daemon: each Telegram session opens a fresh transport
|
||||
/// connection, exactly like a socket client.
|
||||
pub(crate) fn spawn_daemon_bridge(
|
||||
codex_home: PathBuf,
|
||||
transport_event_tx: mpsc::Sender<TransportEvent>,
|
||||
shutdown: CancellationToken,
|
||||
) -> JoinHandle<()> {
|
||||
let connector: Connector = Box::new(move || {
|
||||
let transport_event_tx = transport_event_tx.clone();
|
||||
Box::pin(async move {
|
||||
let connection_id = akode_app_server_transport::next_connection_id();
|
||||
let (writer_tx, writer_rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let (to_bridge, from_server) = mpsc::unbounded_channel();
|
||||
let (to_server, mut from_bridge) = mpsc::unbounded_channel::<JSONRPCMessage>();
|
||||
let disconnect = CancellationToken::new();
|
||||
transport_event_tx
|
||||
.send(TransportEvent::ConnectionOpened {
|
||||
connection_id,
|
||||
origin: ConnectionOrigin::InProcess,
|
||||
auth: None,
|
||||
writer: writer_tx,
|
||||
disconnect_sender: Some(disconnect.clone()),
|
||||
})
|
||||
.await
|
||||
.ok()?;
|
||||
let forward = forward_writer(writer_rx, to_bridge);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::select! {
|
||||
() = disconnect.cancelled() => break,
|
||||
message = from_bridge.recv() => {
|
||||
let Some(message) = message else { break };
|
||||
if transport_event_tx
|
||||
.send(TransportEvent::IncomingMessage { connection_id, message })
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
forward.abort();
|
||||
let _ = transport_event_tx
|
||||
.send(TransportEvent::ConnectionClosed { connection_id })
|
||||
.await;
|
||||
});
|
||||
Some(BridgeConnection {
|
||||
to_server,
|
||||
from_server,
|
||||
})
|
||||
})
|
||||
});
|
||||
tokio::spawn(akode_telegram::bridge::run_supervisor(
|
||||
BridgeOptions::new(codex_home),
|
||||
connector,
|
||||
shutdown,
|
||||
))
|
||||
}
|
||||
|
||||
/// Id of the bridge connection inside an in-process app-server (the client uses 0).
|
||||
pub(crate) const IN_PROCESS_BRIDGE_CONNECTION_ID: ConnectionId = ConnectionId(u64::MAX);
|
||||
|
||||
/// Events from the bridge to the in-process processor loop.
|
||||
pub(crate) enum InProcessBridgeEvent {
|
||||
Opened(mpsc::UnboundedSender<JSONRPCMessage>),
|
||||
Message(JSONRPCMessage),
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// Starts the bridge for an in-process app-server. The processor loop owns the
|
||||
/// connection state and receives [`InProcessBridgeEvent`]s.
|
||||
pub(crate) fn spawn_in_process_bridge(
|
||||
codex_home: PathBuf,
|
||||
events: mpsc::UnboundedSender<InProcessBridgeEvent>,
|
||||
shutdown: CancellationToken,
|
||||
) -> JoinHandle<()> {
|
||||
let connector: Connector = Box::new(move || {
|
||||
let events = events.clone();
|
||||
Box::pin(async move {
|
||||
let (to_bridge, from_server) = mpsc::unbounded_channel();
|
||||
let (to_server, mut from_bridge) = mpsc::unbounded_channel::<JSONRPCMessage>();
|
||||
events.send(InProcessBridgeEvent::Opened(to_bridge)).ok()?;
|
||||
tokio::spawn(async move {
|
||||
while let Some(message) = from_bridge.recv().await {
|
||||
if events.send(InProcessBridgeEvent::Message(message)).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = events.send(InProcessBridgeEvent::Closed);
|
||||
});
|
||||
Some(BridgeConnection {
|
||||
to_server,
|
||||
from_server,
|
||||
})
|
||||
})
|
||||
});
|
||||
tokio::spawn(akode_telegram::bridge::run_supervisor(
|
||||
BridgeOptions::new(codex_home),
|
||||
connector,
|
||||
shutdown,
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user