- Shift+Tab: default, plan, accesso completo (preset di /permissions, saltato se i requisiti non lo permettono; uscendo tornano i permessi di prima). Modalità sotto il riquadro di scrittura, a sinistra, e in /stato su Telegram. - Telegram: topic creato al primo turno; sessioni chiuse senza turni perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi; topic di «Nuova chat» assegnati con i pulsanti, i comandi lì ricevono risposta nella chat principale; pulizia all'avvio. - Versione 0.3.1 e novità nel README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2443 lines
90 KiB
Rust
2443 lines
90 KiB
Rust
//! The bridge: an app-server client that mirrors sessions to Telegram and acts on replies.
|
|
//!
|
|
//! Each session gets its own topic in every allowed private chat (when the bot has topics
|
|
//! enabled); text written in a topic goes to that session. Without topics everything goes
|
|
//! to the main chat with a `[cwd · model]` tag and the session is chosen with buttons.
|
|
//! Buttons carry opaque random tokens; what they do is kept here, never in the button.
|
|
|
|
use std::collections::HashMap;
|
|
use std::collections::VecDeque;
|
|
use std::future::Future;
|
|
use std::path::PathBuf;
|
|
use std::pin::Pin;
|
|
use std::sync::Arc;
|
|
use std::sync::Mutex;
|
|
use std::time::Duration;
|
|
use std::time::Instant;
|
|
|
|
use akode_app_server_protocol::ClientInfo;
|
|
use akode_app_server_protocol::ClientNotification;
|
|
use akode_app_server_protocol::ClientRequest;
|
|
use akode_app_server_protocol::CodexErrorInfo;
|
|
use akode_app_server_protocol::CommandExecutionApprovalDecision;
|
|
use akode_app_server_protocol::CommandExecutionRequestApprovalResponse;
|
|
use akode_app_server_protocol::CommandExecutionStatus;
|
|
use akode_app_server_protocol::ErrorNotification;
|
|
use akode_app_server_protocol::FileChangeApprovalDecision;
|
|
use akode_app_server_protocol::FileChangeRequestApprovalResponse;
|
|
use akode_app_server_protocol::FileUpdateChange;
|
|
use akode_app_server_protocol::GrantedPermissionProfile;
|
|
use akode_app_server_protocol::InitializeCapabilities;
|
|
use akode_app_server_protocol::InitializeParams;
|
|
use akode_app_server_protocol::JSONRPCMessage;
|
|
use akode_app_server_protocol::JSONRPCResponse;
|
|
use akode_app_server_protocol::PatchApplyStatus;
|
|
use akode_app_server_protocol::PermissionGrantScope;
|
|
use akode_app_server_protocol::PermissionsRequestApprovalResponse;
|
|
use akode_app_server_protocol::RequestId;
|
|
use akode_app_server_protocol::RequestPermissionProfile;
|
|
use akode_app_server_protocol::ServerNotification;
|
|
use akode_app_server_protocol::ServerRequest;
|
|
use akode_app_server_protocol::Thread;
|
|
use akode_app_server_protocol::ThreadItem;
|
|
use akode_app_server_protocol::ThreadItemPayload;
|
|
use akode_app_server_protocol::ThreadLoadedListParams;
|
|
use akode_app_server_protocol::ThreadLoadedListResponse;
|
|
use akode_app_server_protocol::ThreadQueueAddParams;
|
|
use akode_app_server_protocol::ThreadResumeParams;
|
|
use akode_app_server_protocol::ThreadResumeResponse;
|
|
use akode_app_server_protocol::ThreadStartParams;
|
|
use akode_app_server_protocol::ThreadStartResponse;
|
|
use akode_app_server_protocol::ThreadStatus;
|
|
use akode_app_server_protocol::Turn;
|
|
use akode_app_server_protocol::TurnInterruptParams;
|
|
use akode_app_server_protocol::TurnPlanStep;
|
|
use akode_app_server_protocol::TurnPlanStepStatus;
|
|
use akode_app_server_protocol::TurnStartParams;
|
|
use akode_app_server_protocol::TurnStatus;
|
|
use akode_app_server_protocol::TurnSteerParams;
|
|
use akode_app_server_protocol::UserInput;
|
|
use tokio::sync::mpsc;
|
|
use tokio::task::JoinHandle;
|
|
use tokio_util::sync::CancellationToken;
|
|
use tracing::info;
|
|
use tracing::warn;
|
|
|
|
use crate::CLIENT_NAME;
|
|
use crate::TELEGRAM_API_BASE;
|
|
use crate::api::ApiError;
|
|
use crate::api::Button;
|
|
use crate::api::CallbackQuery;
|
|
use crate::api::Message;
|
|
use crate::api::TelegramApi;
|
|
use crate::api::Update;
|
|
use crate::lock::PollLock;
|
|
use crate::outbox::Dest;
|
|
use crate::outbox::Feedback;
|
|
use crate::outbox::Outbox;
|
|
use crate::outbox::OutboxTask;
|
|
use crate::outbox::Tag;
|
|
use crate::pairing;
|
|
use crate::settings::TelegramSettings;
|
|
use crate::settings::Toggle;
|
|
use crate::settings::load_token;
|
|
use crate::settings::set_toggle;
|
|
use crate::text;
|
|
use crate::text::Rich;
|
|
use crate::topics::TopicEntry;
|
|
use crate::topics::Topics;
|
|
use crate::topics::has_rollout;
|
|
|
|
/// Channels of one internal app-server connection.
|
|
pub struct BridgeConnection {
|
|
pub to_server: mpsc::UnboundedSender<JSONRPCMessage>,
|
|
pub from_server: mpsc::UnboundedReceiver<JSONRPCMessage>,
|
|
}
|
|
|
|
pub type ConnectFuture = Pin<Box<dyn Future<Output = Option<BridgeConnection>> + Send>>;
|
|
|
|
/// Opens a new internal connection to the hosting app-server.
|
|
pub type Connector = Box<dyn FnMut() -> ConnectFuture + Send>;
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct BridgeOptions {
|
|
pub codex_home: PathBuf,
|
|
pub api_base: String,
|
|
/// How often the settings are re-read (enable/disable, new chats).
|
|
pub settings_poll: Duration,
|
|
/// `getUpdates` long-poll timeout.
|
|
pub long_poll_secs: u64,
|
|
/// At most one draft update per session in this interval.
|
|
pub draft_interval: Duration,
|
|
}
|
|
|
|
impl BridgeOptions {
|
|
pub fn new(codex_home: PathBuf) -> Self {
|
|
Self {
|
|
codex_home,
|
|
api_base: TELEGRAM_API_BASE.to_string(),
|
|
settings_poll: Duration::from_secs(5),
|
|
long_poll_secs: 25,
|
|
draft_interval: Duration::from_secs(1),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Notifications the bridge never needs (streaming deltas other than the answer's).
|
|
const OPTED_OUT_NOTIFICATIONS: &[&str] = &[
|
|
"item/plan/delta",
|
|
"item/reasoning/summaryTextDelta",
|
|
"item/reasoning/summaryPartAdded",
|
|
"item/reasoning/textDelta",
|
|
"item/commandExecution/outputDelta",
|
|
"item/commandExecution/terminalInteraction",
|
|
"item/fileChange/outputDelta",
|
|
"item/mcpToolCall/progress",
|
|
"command/exec/outputDelta",
|
|
"process/outputDelta",
|
|
"turn/diff/updated",
|
|
"rawResponseItem/completed",
|
|
"rawResponse/completed",
|
|
"fs/changed",
|
|
"fuzzyFileSearch/sessionUpdated",
|
|
"thread/realtime/outputAudio/delta",
|
|
"thread/realtime/transcript/delta",
|
|
];
|
|
|
|
const LOOP_GUARD_PREFIX: &str = "Il modello ripete lo stesso comando";
|
|
const MAX_ROUTES: usize = 2000;
|
|
const MAX_CALLBACKS: usize = 2000;
|
|
/// A draft disappears after about 30 seconds: refresh it while the turn is silent.
|
|
const DRAFT_KEEPALIVE: Duration = Duration::from_secs(20);
|
|
/// Characters of the running answer shown in a draft (its tail).
|
|
const DRAFT_TAIL: usize = 3500;
|
|
/// `getMe` is re-read every this many settings ticks (topics may have been enabled).
|
|
const PROBE_TICKS: u64 = 60;
|
|
/// Standard Telegram reactions: received, done.
|
|
const REACTION_RECEIVED: &str = "\u{1F440}";
|
|
const REACTION_DONE: &str = "\u{1F44D}";
|
|
/// Telegram shows at most 200 characters in a button answer.
|
|
const ANSWER_LIMIT: usize = 200;
|
|
|
|
/// Runs until `shutdown`: serves the bot while it is enabled, configured and this process
|
|
/// holds the poll lock; otherwise waits and checks again. Contacts nobody while disabled.
|
|
pub async fn run_supervisor(
|
|
options: BridgeOptions,
|
|
mut connector: Connector,
|
|
shutdown: CancellationToken,
|
|
) {
|
|
loop {
|
|
let settings = TelegramSettings::load(&options.codex_home);
|
|
if settings.enabled
|
|
&& let Some(lock) = PollLock::try_acquire(&options.codex_home)
|
|
&& let Some(token) = load_token(&options.codex_home, settings.key_store)
|
|
{
|
|
if let Some(connection) = connector().await {
|
|
info!("telegram: bridge started");
|
|
let api = TelegramApi::with_base_url(&options.api_base, &token);
|
|
Bridge::new(options.clone(), api, settings, token)
|
|
.run(connection, &shutdown)
|
|
.await;
|
|
info!("telegram: bridge stopped");
|
|
}
|
|
drop(lock);
|
|
}
|
|
tokio::select! {
|
|
() = shutdown.cancelled() => return,
|
|
() = tokio::time::sleep(options.settings_poll) => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Live draft of the running answer.
|
|
struct Stream {
|
|
draft_id: i64,
|
|
item_id: String,
|
|
text: String,
|
|
last_sent: Option<Instant>,
|
|
dirty: bool,
|
|
stopped: bool,
|
|
}
|
|
|
|
/// The plan message of the current turn.
|
|
struct Plan {
|
|
turn_id: String,
|
|
text: String,
|
|
version: u64,
|
|
messages: Vec<(i64, i64)>,
|
|
}
|
|
|
|
struct Session {
|
|
thread_id: String,
|
|
cwd: PathBuf,
|
|
model: String,
|
|
busy: bool,
|
|
active_turn: Option<String>,
|
|
last_message: Option<String>,
|
|
/// (tokens in context, output tokens of the last request, context window).
|
|
usage: Option<(i64, i64, Option<i64>)>,
|
|
stream: Option<Stream>,
|
|
plan: Option<Plan>,
|
|
/// User messages that started or joined the running turn (for the done reaction).
|
|
reactions: Vec<(i64, i64)>,
|
|
/// The running turn was asked for from Telegram: its answer is always sent.
|
|
from_telegram: bool,
|
|
/// The session had a turn (its topic is created lazily, at the first one).
|
|
had_turn: bool,
|
|
/// `default`, `plan` or `accesso completo` (as cycled with Shift+Tab in the TUI).
|
|
mode: &'static str,
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
enum ApprovalKind {
|
|
Command,
|
|
FileChange,
|
|
Permissions,
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
enum Choice {
|
|
Accept,
|
|
AcceptAlways,
|
|
Decline,
|
|
}
|
|
|
|
struct Approval {
|
|
key: u64,
|
|
request_id: RequestId,
|
|
thread_id: String,
|
|
item_id: Option<String>,
|
|
kind: ApprovalKind,
|
|
text: Rich,
|
|
permissions: Option<RequestPermissionProfile>,
|
|
messages: Vec<(i64, i64)>,
|
|
/// Final line once answered (here or elsewhere).
|
|
outcome: Option<String>,
|
|
answered_here: bool,
|
|
}
|
|
|
|
/// What a button does, kept server-side under an opaque token.
|
|
#[derive(Clone, Debug)]
|
|
enum Action {
|
|
Approve { key: u64, choice: Choice },
|
|
Stop(String),
|
|
Status(String),
|
|
RefreshSessions,
|
|
NewSessionMenu,
|
|
NewSession(String),
|
|
SendTo { pending: u64, thread_id: String },
|
|
/// Gives an unmapped topic to a session (`None`: a new one in `cwd`) and sends the text.
|
|
Adopt {
|
|
pending: u64,
|
|
thread_id: Option<String>,
|
|
cwd: Option<String>,
|
|
},
|
|
Toggle(Toggle),
|
|
}
|
|
|
|
/// A message waiting for the user to pick its session.
|
|
struct PendingText {
|
|
chat_id: i64,
|
|
message_id: i64,
|
|
text: String,
|
|
/// Written in this unmapped topic (created by the user with «Nuova chat»).
|
|
topic: Option<i64>,
|
|
}
|
|
|
|
enum Pending {
|
|
Init,
|
|
LoadedList,
|
|
Resume,
|
|
NewThread {
|
|
chat_id: i64,
|
|
thread: Option<i64>,
|
|
/// A message written in an unmapped topic: that topic becomes the session's.
|
|
adopt: Option<PendingText>,
|
|
},
|
|
Start {
|
|
chat_id: i64,
|
|
thread_id: String,
|
|
message_id: Option<i64>,
|
|
},
|
|
Steer {
|
|
chat_id: i64,
|
|
thread_id: String,
|
|
text: String,
|
|
message_id: Option<i64>,
|
|
},
|
|
Queue {
|
|
chat_id: i64,
|
|
thread_id: String,
|
|
message_id: Option<i64>,
|
|
},
|
|
Interrupt {
|
|
chat_id: Option<i64>,
|
|
thread_id: String,
|
|
},
|
|
}
|
|
|
|
/// Where a command came from: replies go back there.
|
|
#[derive(Clone, Copy, Debug)]
|
|
struct Origin {
|
|
chat_id: i64,
|
|
thread: Option<i64>,
|
|
}
|
|
|
|
struct AbortOnDrop(JoinHandle<()>);
|
|
|
|
impl Drop for AbortOnDrop {
|
|
fn drop(&mut self) {
|
|
self.0.abort();
|
|
}
|
|
}
|
|
|
|
pub(crate) struct Bridge {
|
|
options: BridgeOptions,
|
|
api: TelegramApi,
|
|
settings: TelegramSettings,
|
|
token: String,
|
|
to_server: Option<mpsc::UnboundedSender<JSONRPCMessage>>,
|
|
outbox: Option<mpsc::UnboundedSender<Outbox>>,
|
|
topics: Arc<Mutex<Topics>>,
|
|
next_request: u64,
|
|
pending: HashMap<RequestId, Pending>,
|
|
sessions: Vec<Session>,
|
|
routes: VecDeque<((i64, i64), String)>,
|
|
approvals: Vec<Approval>,
|
|
next_approval: u64,
|
|
file_changes: HashMap<String, Vec<FileUpdateChange>>,
|
|
callbacks: HashMap<String, Action>,
|
|
callback_order: VecDeque<String>,
|
|
pending_texts: HashMap<u64, PendingText>,
|
|
next_pending_text: u64,
|
|
/// Latest `/sessioni` message per chat and the content it shows.
|
|
session_lists: HashMap<i64, (i64, String)>,
|
|
next_draft: i64,
|
|
drafts_supported: bool,
|
|
}
|
|
|
|
fn yes_no(value: bool) -> &'static str {
|
|
if value { "Sì" } else { "No" }
|
|
}
|
|
|
|
impl Bridge {
|
|
fn new(options: BridgeOptions, api: TelegramApi, settings: TelegramSettings, token: String) -> Self {
|
|
let topics = Arc::new(Mutex::new(Topics::load(&options.codex_home)));
|
|
Self {
|
|
options,
|
|
api,
|
|
settings,
|
|
token,
|
|
to_server: None,
|
|
outbox: None,
|
|
topics,
|
|
next_request: 0,
|
|
pending: HashMap::new(),
|
|
sessions: Vec::new(),
|
|
routes: VecDeque::new(),
|
|
approvals: Vec::new(),
|
|
next_approval: 0,
|
|
file_changes: HashMap::new(),
|
|
callbacks: HashMap::new(),
|
|
callback_order: VecDeque::new(),
|
|
pending_texts: HashMap::new(),
|
|
next_pending_text: 0,
|
|
session_lists: HashMap::new(),
|
|
next_draft: 0,
|
|
drafts_supported: true,
|
|
}
|
|
}
|
|
|
|
async fn run(mut self, connection: BridgeConnection, shutdown: &CancellationToken) {
|
|
let BridgeConnection {
|
|
to_server,
|
|
mut from_server,
|
|
} = connection;
|
|
self.to_server = Some(to_server);
|
|
let (outbox_tx, outbox_rx) = mpsc::unbounded_channel();
|
|
let (feedback_tx, mut feedback_rx) = mpsc::unbounded_channel();
|
|
let (updates_tx, mut updates_rx) = mpsc::channel(8);
|
|
let outbox = OutboxTask {
|
|
api: self.api.clone(),
|
|
topics: Arc::clone(&self.topics),
|
|
codex_home: self.options.codex_home.clone(),
|
|
feedback: feedback_tx,
|
|
};
|
|
let _outbox_task = AbortOnDrop(tokio::spawn(outbox.run(outbox_rx)));
|
|
let _poll_task = AbortOnDrop(tokio::spawn(run_poller(
|
|
self.api.clone(),
|
|
self.options.long_poll_secs,
|
|
updates_tx,
|
|
)));
|
|
self.outbox = Some(outbox_tx);
|
|
// Learn the bot (topics, username) before any session message is queued.
|
|
self.post(Outbox::Setup { commands: true });
|
|
self.initialize();
|
|
let mut ticks = tokio::time::interval(self.options.settings_poll);
|
|
ticks.tick().await;
|
|
let mut draft_ticks = tokio::time::interval(Duration::from_millis(200));
|
|
let mut tick_count: u64 = 0;
|
|
loop {
|
|
tokio::select! {
|
|
() = shutdown.cancelled() => break,
|
|
message = from_server.recv() => {
|
|
let Some(message) = message else { break };
|
|
self.on_server_message(message);
|
|
}
|
|
updates = updates_rx.recv() => {
|
|
match updates {
|
|
Some(Ok(updates)) => {
|
|
for update in updates {
|
|
self.on_update(update);
|
|
}
|
|
}
|
|
Some(Err(err)) => {
|
|
warn!("telegram: the bot token was refused, stopping: {err}");
|
|
break;
|
|
}
|
|
None => break,
|
|
}
|
|
}
|
|
feedback = feedback_rx.recv() => {
|
|
match feedback {
|
|
Some(Feedback::Sent { tag, chat_id, message_id }) => {
|
|
self.on_sent(tag, chat_id, message_id);
|
|
}
|
|
Some(Feedback::DraftFailed) => {
|
|
self.drafts_supported = false;
|
|
for session in &mut self.sessions {
|
|
session.stream = None;
|
|
}
|
|
}
|
|
None => {}
|
|
}
|
|
}
|
|
_ = draft_ticks.tick() => self.flush_drafts(),
|
|
_ = ticks.tick() => {
|
|
tick_count += 1;
|
|
self.settings = TelegramSettings::load(&self.options.codex_home);
|
|
if !self.settings.enabled {
|
|
break;
|
|
}
|
|
if tick_count.is_multiple_of(6)
|
|
&& load_token(&self.options.codex_home, self.settings.key_store).as_deref()
|
|
!= Some(self.token.as_str())
|
|
{
|
|
break;
|
|
}
|
|
if tick_count.is_multiple_of(PROBE_TICKS) {
|
|
self.post(Outbox::Setup { commands: false });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- app-server side -------------------------------------------------------------
|
|
|
|
fn send_to_server(&self, message: JSONRPCMessage) {
|
|
if let Some(tx) = &self.to_server {
|
|
let _ = tx.send(message);
|
|
}
|
|
}
|
|
|
|
fn request(&mut self, build: impl FnOnce(RequestId) -> ClientRequest, pending: Pending) {
|
|
self.next_request += 1;
|
|
let id = RequestId::String(format!("tg-{}", self.next_request));
|
|
let request = build(id.clone());
|
|
match serde_json::to_value(request).and_then(serde_json::from_value) {
|
|
Ok(request) => {
|
|
self.pending.insert(id, pending);
|
|
self.send_to_server(JSONRPCMessage::Request(request));
|
|
}
|
|
Err(err) => warn!("telegram: cannot encode a request: {err}"),
|
|
}
|
|
}
|
|
|
|
fn initialize(&mut self) {
|
|
let params = InitializeParams {
|
|
client_info: ClientInfo {
|
|
name: CLIENT_NAME.to_string(),
|
|
title: Some("aKode Telegram".to_string()),
|
|
version: env!("CARGO_PKG_VERSION").to_string(),
|
|
},
|
|
capabilities: Some(InitializeCapabilities {
|
|
experimental_api: true,
|
|
opt_out_notification_methods: Some(
|
|
OPTED_OUT_NOTIFICATIONS.iter().map(ToString::to_string).collect(),
|
|
),
|
|
..Default::default()
|
|
}),
|
|
};
|
|
self.request(
|
|
|request_id| ClientRequest::Initialize { request_id, params },
|
|
Pending::Init,
|
|
);
|
|
}
|
|
|
|
fn on_server_message(&mut self, message: JSONRPCMessage) {
|
|
match message {
|
|
JSONRPCMessage::Response(response) => {
|
|
if let Some(pending) = self.pending.remove(&response.id) {
|
|
self.on_response(pending, Ok(response.result));
|
|
}
|
|
}
|
|
JSONRPCMessage::Error(error) => {
|
|
if let Some(pending) = self.pending.remove(&error.id) {
|
|
self.on_response(pending, Err(error.error.message));
|
|
}
|
|
}
|
|
JSONRPCMessage::Notification(notification) => {
|
|
if let Ok(notification) = ServerNotification::try_from(notification) {
|
|
self.on_notification(notification);
|
|
}
|
|
}
|
|
JSONRPCMessage::Request(request) => {
|
|
if let Ok(request) = ServerRequest::try_from(request) {
|
|
self.on_server_request(request);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_response(&mut self, pending: Pending, result: Result<serde_json::Value, String>) {
|
|
match pending {
|
|
Pending::Init => {
|
|
if let Err(err) = result {
|
|
warn!("telegram: initialize failed: {err}");
|
|
return;
|
|
}
|
|
if let Ok(serde_json::Value::Object(notification)) =
|
|
serde_json::to_value(ClientNotification::Initialized)
|
|
&& let Ok(notification) =
|
|
serde_json::from_value(serde_json::Value::Object(notification))
|
|
{
|
|
self.send_to_server(JSONRPCMessage::Notification(notification));
|
|
}
|
|
self.request(
|
|
|request_id| ClientRequest::ThreadLoadedList {
|
|
request_id,
|
|
params: ThreadLoadedListParams {
|
|
cursor: None,
|
|
limit: Some(200),
|
|
},
|
|
},
|
|
Pending::LoadedList,
|
|
);
|
|
}
|
|
Pending::LoadedList => {
|
|
let Ok(list) = result.and_then(|value| {
|
|
serde_json::from_value::<ThreadLoadedListResponse>(value)
|
|
.map_err(|err| err.to_string())
|
|
}) else {
|
|
return;
|
|
};
|
|
self.clean_topics(&list.data);
|
|
for thread_id in list.data {
|
|
if self.session(&thread_id).is_some() {
|
|
continue;
|
|
}
|
|
self.request(
|
|
|request_id| ClientRequest::ThreadResume {
|
|
request_id,
|
|
params: ThreadResumeParams {
|
|
thread_id,
|
|
..Default::default()
|
|
},
|
|
},
|
|
Pending::Resume,
|
|
);
|
|
}
|
|
}
|
|
Pending::Resume => {
|
|
if let Ok(response) = result.and_then(|value| {
|
|
serde_json::from_value::<ThreadResumeResponse>(value)
|
|
.map_err(|err| err.to_string())
|
|
}) {
|
|
let model = response.model.clone();
|
|
let mode = session_mode(None, &response.sandbox);
|
|
self.add_session(&response.thread, Some(model), mode);
|
|
}
|
|
}
|
|
Pending::NewThread {
|
|
chat_id,
|
|
thread,
|
|
adopt,
|
|
} => {
|
|
let origin = Origin { chat_id, thread };
|
|
match result.and_then(|value| {
|
|
serde_json::from_value::<ThreadStartResponse>(value)
|
|
.map_err(|err| err.to_string())
|
|
}) {
|
|
Ok(response) => {
|
|
let model = response.model.clone();
|
|
let mode = session_mode(None, &response.sandbox);
|
|
self.add_session(&response.thread, Some(model), mode);
|
|
let thread_id = response.thread.id.clone();
|
|
if let Some(text) = adopt {
|
|
self.adopt_topic(text, &thread_id);
|
|
return;
|
|
}
|
|
let name = self.topic_name(&thread_id);
|
|
let note = if self.topics_enabled() {
|
|
format!(
|
|
"Nuova sessione avviata: {name}. Rispondi a questo messaggio con la \
|
|
prima richiesta: il topic della sessione nasce con il primo turno."
|
|
)
|
|
} else {
|
|
format!(
|
|
"Nuova sessione avviata: {name}. Rispondi a questo messaggio con la \
|
|
prima richiesta."
|
|
)
|
|
};
|
|
self.say_with(origin, Rich::plain(note), None, Tag::Session(thread_id));
|
|
}
|
|
Err(err) => self.say(origin, &format!("Sessione non avviata: {err}")),
|
|
}
|
|
}
|
|
Pending::Start {
|
|
chat_id,
|
|
thread_id,
|
|
message_id,
|
|
} => match result {
|
|
Ok(_) => self.accepted(chat_id, &thread_id, message_id, "Inviato: il turno è partito."),
|
|
Err(err) => self.say_to(chat_id, &thread_id, &format!("Non inviato: {err}")),
|
|
},
|
|
Pending::Steer {
|
|
chat_id,
|
|
thread_id,
|
|
text,
|
|
message_id,
|
|
} => match result {
|
|
Ok(_) => self.accepted(chat_id, &thread_id, message_id, "Aggiunto al turno in corso."),
|
|
Err(_) => {
|
|
let queue_thread = thread_id.clone();
|
|
self.request(
|
|
|request_id| ClientRequest::ThreadQueueAdd {
|
|
request_id,
|
|
params: ThreadQueueAddParams {
|
|
thread_id: queue_thread,
|
|
input: user_input(text),
|
|
client_user_message_id: uuid::Uuid::new_v4().to_string(),
|
|
responsesapi_client_metadata: None,
|
|
},
|
|
},
|
|
Pending::Queue {
|
|
chat_id,
|
|
thread_id,
|
|
message_id,
|
|
},
|
|
);
|
|
}
|
|
},
|
|
Pending::Queue {
|
|
chat_id,
|
|
thread_id,
|
|
message_id,
|
|
} => match result {
|
|
Ok(_) => self.accepted(
|
|
chat_id,
|
|
&thread_id,
|
|
message_id,
|
|
"In coda: partirà alla fine del turno in corso.",
|
|
),
|
|
Err(err) => self.say_to(chat_id, &thread_id, &format!("Non inviato: {err}")),
|
|
},
|
|
Pending::Interrupt { chat_id, thread_id } => match (result, chat_id) {
|
|
(Ok(_), Some(chat_id)) => self.say_to(chat_id, &thread_id, "Interruzione richiesta."),
|
|
(Err(err), Some(chat_id)) => {
|
|
self.say_to(chat_id, &thread_id, &format!("Interruzione non riuscita: {err}"))
|
|
}
|
|
(_, None) => {}
|
|
},
|
|
}
|
|
}
|
|
|
|
/// A user message reached the session: a reaction when enabled, else a short note.
|
|
fn accepted(&mut self, chat_id: i64, thread_id: &str, message_id: Option<i64>, note: &str) {
|
|
let react = self.settings.reactions;
|
|
if let Some(session) = self.session_mut(thread_id) {
|
|
session.from_telegram = true;
|
|
if let Some(message_id) = message_id.filter(|_| react) {
|
|
session.reactions.push((chat_id, message_id));
|
|
}
|
|
}
|
|
match message_id.filter(|_| react) {
|
|
Some(message_id) => self.post(Outbox::React {
|
|
chat_id,
|
|
message_id,
|
|
emoji: REACTION_RECEIVED,
|
|
}),
|
|
None => self.say_to(chat_id, thread_id, note),
|
|
}
|
|
}
|
|
|
|
fn add_session(&mut self, thread: &Thread, model: Option<String>, mode: &'static str) {
|
|
if thread.parent_thread_id.is_some() || self.session(&thread.id).is_some() {
|
|
return;
|
|
}
|
|
let busy = matches!(thread.status, ThreadStatus::Active { .. });
|
|
let active_turn = thread
|
|
.turns
|
|
.iter()
|
|
.rev()
|
|
.find(|turn| turn.status == TurnStatus::InProgress)
|
|
.map(|turn| turn.id.clone());
|
|
self.sessions.push(Session {
|
|
thread_id: thread.id.clone(),
|
|
cwd: thread.cwd.to_path_buf(),
|
|
model: model.or_else(|| thread.model.clone()).unwrap_or_default(),
|
|
busy: busy || active_turn.is_some(),
|
|
active_turn,
|
|
last_message: None,
|
|
usage: None,
|
|
stream: None,
|
|
plan: None,
|
|
reactions: Vec::new(),
|
|
from_telegram: false,
|
|
had_turn: !thread.turns.is_empty(),
|
|
mode,
|
|
});
|
|
self.lock_topics()
|
|
.remember_cwd(&thread.cwd.to_path_buf().display().to_string());
|
|
// An existing topic gets its name back; a new one waits for the first turn.
|
|
self.ensure_topics(&thread.id, false);
|
|
self.refresh_session_lists();
|
|
}
|
|
|
|
fn session(&self, thread_id: &str) -> Option<&Session> {
|
|
self.sessions.iter().find(|session| session.thread_id == thread_id)
|
|
}
|
|
|
|
fn session_mut(&mut self, thread_id: &str) -> Option<&mut Session> {
|
|
self.sessions
|
|
.iter_mut()
|
|
.find(|session| session.thread_id == thread_id)
|
|
}
|
|
|
|
fn lock_topics(&self) -> std::sync::MutexGuard<'_, Topics> {
|
|
self.topics
|
|
.lock()
|
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
}
|
|
|
|
fn topics_enabled(&self) -> bool {
|
|
self.lock_topics().enabled
|
|
}
|
|
|
|
fn topic_name(&self, thread_id: &str) -> String {
|
|
match self.session(thread_id) {
|
|
Some(session) => text::topic_name(
|
|
&session.cwd,
|
|
&self.settings.model_display_name(&session.model),
|
|
),
|
|
None => "aKode".to_string(),
|
|
}
|
|
}
|
|
|
|
fn tag(&self, thread_id: &str) -> String {
|
|
format!("[{}]", self.topic_name(thread_id))
|
|
}
|
|
|
|
/// Asks the outbox to rename the session's topic in every chat and, with `create`, to
|
|
/// create it when missing.
|
|
fn ensure_topics(&self, thread_id: &str, create: bool) {
|
|
let name = self.topic_name(thread_id);
|
|
for chat_id in &self.settings.allowed_chat_ids {
|
|
self.post(Outbox::Topic {
|
|
chat_id: *chat_id,
|
|
session: thread_id.to_string(),
|
|
name: name.clone(),
|
|
create,
|
|
});
|
|
}
|
|
}
|
|
|
|
/// The session is gone: its topic is deleted when the session never had a turn,
|
|
/// otherwise renamed to «… (chiusa)».
|
|
fn close_topics(&self, thread_id: &str) {
|
|
let Some(session) = self.session(thread_id) else {
|
|
return;
|
|
};
|
|
let empty = !session.had_turn && !has_rollout(&self.options.codex_home, thread_id);
|
|
let name = closed_name(&self.topic_name(thread_id));
|
|
for chat_id in &self.settings.allowed_chat_ids {
|
|
let thread = self.lock_topics().entry(*chat_id, thread_id).map(|e| e.thread);
|
|
match thread {
|
|
Some(thread) if empty => self.post(Outbox::DeleteTopic {
|
|
chat_id: *chat_id,
|
|
thread,
|
|
session: Some(thread_id.to_string()),
|
|
fallback_name: Some(name.clone()),
|
|
}),
|
|
Some(_) => self.post(Outbox::Topic {
|
|
chat_id: *chat_id,
|
|
session: thread_id.to_string(),
|
|
name: name.clone(),
|
|
create: false,
|
|
}),
|
|
None => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// At start: topics of sessions that are gone without ever having a turn are deleted,
|
|
/// renames that Telegram never confirmed are sent again.
|
|
fn clean_topics(&self, loaded: &[String]) {
|
|
let entries = self.lock_topics().entries();
|
|
for entry in entries {
|
|
if !self.settings.is_allowed(entry.chat_id)
|
|
|| loaded.iter().any(|id| id == &entry.session)
|
|
{
|
|
continue;
|
|
}
|
|
if !has_rollout(&self.options.codex_home, &entry.session) {
|
|
self.post(Outbox::DeleteTopic {
|
|
chat_id: entry.chat_id,
|
|
thread: entry.thread,
|
|
session: Some(entry.session.clone()),
|
|
fallback_name: Some(closed_name(&entry.name)),
|
|
});
|
|
} else if let Some(name) = entry.pending_name {
|
|
self.post(Outbox::Topic {
|
|
chat_id: entry.chat_id,
|
|
session: entry.session,
|
|
name,
|
|
create: false,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_notification(&mut self, notification: ServerNotification) {
|
|
match notification {
|
|
ServerNotification::ThreadStarted(started) => {
|
|
let model = started.thread.model.clone();
|
|
self.add_session(&started.thread, model, MODE_DEFAULT);
|
|
}
|
|
ServerNotification::ThreadClosed(closed) => {
|
|
self.close_topics(&closed.thread_id);
|
|
self.sessions
|
|
.retain(|session| session.thread_id != closed.thread_id);
|
|
self.refresh_session_lists();
|
|
}
|
|
ServerNotification::ThreadSettingsUpdated(updated) => {
|
|
let settings = updated.thread_settings;
|
|
let Some(session) = self.session_mut(&updated.thread_id) else {
|
|
return;
|
|
};
|
|
let cwd = settings.cwd.to_path_buf();
|
|
session.mode = session_mode(
|
|
serde_json::to_value(settings.collaboration_mode.mode).ok(),
|
|
&settings.sandbox_policy,
|
|
);
|
|
if session.model != settings.model || session.cwd != cwd {
|
|
session.model = settings.model;
|
|
session.cwd = cwd;
|
|
self.ensure_topics(&updated.thread_id, false);
|
|
self.refresh_session_lists();
|
|
}
|
|
}
|
|
ServerNotification::ThreadStatusChanged(changed) => {
|
|
let busy = matches!(changed.status, ThreadStatus::Active { .. });
|
|
if let Some(session) = self.session_mut(&changed.thread_id)
|
|
&& session.busy != busy
|
|
{
|
|
session.busy = busy;
|
|
self.refresh_session_lists();
|
|
}
|
|
}
|
|
ServerNotification::TurnStarted(started) => {
|
|
if let Some(session) = self.session_mut(&started.thread_id) {
|
|
session.busy = true;
|
|
session.active_turn = Some(started.turn.id);
|
|
session.last_message = None;
|
|
session.stream = None;
|
|
session.had_turn = true;
|
|
self.ensure_topics(&started.thread_id, true);
|
|
}
|
|
self.refresh_session_lists();
|
|
}
|
|
ServerNotification::AgentMessageDelta(delta) => {
|
|
self.on_answer_delta(&delta.thread_id, &delta.item_id, &delta.delta);
|
|
}
|
|
ServerNotification::TurnPlanUpdated(updated) => {
|
|
self.on_plan(
|
|
&updated.thread_id,
|
|
&updated.turn_id,
|
|
updated.explanation.as_deref(),
|
|
&updated.plan,
|
|
);
|
|
}
|
|
ServerNotification::ItemStarted(started) => self.on_item(started.item),
|
|
ServerNotification::ItemCompleted(completed) => {
|
|
if let ThreadItemPayload::AgentMessage { text, .. } = &completed.item.payload
|
|
&& let Some(session) = self.session_mut(&completed.thread_id)
|
|
{
|
|
session.last_message = Some(text.clone());
|
|
}
|
|
self.on_item(completed.item);
|
|
}
|
|
ServerNotification::ThreadTokenUsageUpdated(updated) => {
|
|
if let Some(session) = self.session_mut(&updated.thread_id) {
|
|
session.usage = Some((
|
|
updated.token_usage.last.total_tokens,
|
|
updated.token_usage.last.output_tokens,
|
|
updated.token_usage.model_context_window,
|
|
));
|
|
}
|
|
}
|
|
ServerNotification::TurnCompleted(completed) => {
|
|
self.on_turn_completed(&completed.thread_id, &completed.turn);
|
|
}
|
|
ServerNotification::Error(error) => self.on_error(&error),
|
|
ServerNotification::ServerRequestResolved(resolved) => {
|
|
self.on_request_resolved(&resolved.request_id);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
// ---- streaming and plan ------------------------------------------------------------
|
|
|
|
fn streaming(&self) -> bool {
|
|
self.settings.streaming && self.drafts_supported
|
|
}
|
|
|
|
fn on_answer_delta(&mut self, thread_id: &str, item_id: &str, delta: &str) {
|
|
if !self.streaming() {
|
|
return;
|
|
}
|
|
self.next_draft += 1;
|
|
let next_draft = self.next_draft;
|
|
let Some(session) = self.session_mut(thread_id) else {
|
|
return;
|
|
};
|
|
let stream = session.stream.get_or_insert_with(|| Stream {
|
|
draft_id: next_draft,
|
|
item_id: item_id.to_string(),
|
|
text: String::new(),
|
|
last_sent: None,
|
|
dirty: false,
|
|
stopped: false,
|
|
});
|
|
if stream.stopped {
|
|
return;
|
|
}
|
|
if stream.item_id != item_id {
|
|
stream.item_id = item_id.to_string();
|
|
stream.text.clear();
|
|
}
|
|
stream.text.push_str(delta);
|
|
stream.dirty = true;
|
|
self.flush_drafts();
|
|
}
|
|
|
|
/// Sends the drafts that are due: at most one per `draft_interval` per session.
|
|
fn flush_drafts(&mut self) {
|
|
if !self.streaming() {
|
|
return;
|
|
}
|
|
let now = Instant::now();
|
|
let interval = self.options.draft_interval;
|
|
let mut due = Vec::new();
|
|
for session in &mut self.sessions {
|
|
let Some(stream) = session.stream.as_mut() else {
|
|
continue;
|
|
};
|
|
if stream.stopped || stream.text.trim().is_empty() {
|
|
continue;
|
|
}
|
|
let elapsed = stream.last_sent.map(|sent| now.duration_since(sent));
|
|
let send = if stream.dirty {
|
|
elapsed.is_none_or(|elapsed| elapsed >= interval)
|
|
} else {
|
|
elapsed.is_some_and(|elapsed| elapsed >= DRAFT_KEEPALIVE)
|
|
};
|
|
if !send {
|
|
continue;
|
|
}
|
|
stream.last_sent = Some(now);
|
|
stream.dirty = false;
|
|
due.push((
|
|
session.thread_id.clone(),
|
|
stream.draft_id,
|
|
draft_tail(&stream.text),
|
|
));
|
|
}
|
|
for (thread_id, draft_id, body) in due {
|
|
let tag = self.tag(&thread_id);
|
|
for chat_id in self.settings.allowed_chat_ids.iter().filter(|id| **id > 0) {
|
|
self.post(Outbox::Draft {
|
|
chat_id: *chat_id,
|
|
session: thread_id.clone(),
|
|
tag: tag.clone(),
|
|
draft_id,
|
|
text: body.clone(),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_plan(
|
|
&mut self,
|
|
thread_id: &str,
|
|
turn_id: &str,
|
|
explanation: Option<&str>,
|
|
steps: &[TurnPlanStep],
|
|
) {
|
|
if !self.settings.streaming || steps.is_empty() {
|
|
return;
|
|
}
|
|
let mut body = String::from("Piano");
|
|
if let Some(explanation) = explanation.map(str::trim).filter(|e| !e.is_empty()) {
|
|
body.push_str(&format!("\n{}", text::truncate(explanation, 500)));
|
|
}
|
|
for step in steps.iter().take(30) {
|
|
let mark = match step.status {
|
|
TurnPlanStepStatus::Completed => "[x]",
|
|
TurnPlanStepStatus::InProgress => "[>]",
|
|
TurnPlanStepStatus::Pending => "[ ]",
|
|
};
|
|
body.push_str(&format!("\n{mark} {}", text::truncate(step.step.trim(), 300)));
|
|
}
|
|
let body = text::truncate(&body, text::MESSAGE_LIMIT);
|
|
let Some(session) = self.session_mut(thread_id) else {
|
|
return;
|
|
};
|
|
let edits = match session.plan.as_mut() {
|
|
Some(plan) if plan.turn_id == turn_id => {
|
|
if plan.text == body {
|
|
return;
|
|
}
|
|
plan.text = body.clone();
|
|
plan.version += 1;
|
|
plan.messages.clone()
|
|
}
|
|
_ => {
|
|
session.plan = Some(Plan {
|
|
turn_id: turn_id.to_string(),
|
|
text: body.clone(),
|
|
version: 1,
|
|
messages: Vec::new(),
|
|
});
|
|
let tag = Tag::Plan(thread_id.to_string(), 1);
|
|
self.send_session(thread_id, Rich::plain(body), None, tag);
|
|
return;
|
|
}
|
|
};
|
|
for (chat_id, message_id) in edits {
|
|
self.post(Outbox::Edit {
|
|
chat_id,
|
|
message_id,
|
|
text: Rich::plain(body.clone()),
|
|
buttons: None,
|
|
fallback: None,
|
|
});
|
|
}
|
|
}
|
|
|
|
fn on_item(&mut self, item: ThreadItem) {
|
|
let (item_id, declined) = match item.payload {
|
|
ThreadItemPayload::FileChange {
|
|
id,
|
|
changes,
|
|
status,
|
|
} => {
|
|
let declined = status == PatchApplyStatus::Declined;
|
|
self.file_changes.insert(id.clone(), changes);
|
|
if self.file_changes.len() > 200 {
|
|
self.file_changes.clear();
|
|
}
|
|
(id, declined)
|
|
}
|
|
ThreadItemPayload::CommandExecution { id, status, .. } => {
|
|
(id, status == CommandExecutionStatus::Declined)
|
|
}
|
|
_ => return,
|
|
};
|
|
// An approval answered elsewhere: the item now tells how.
|
|
let mut edits = Vec::new();
|
|
for approval in &mut self.approvals {
|
|
if approval.item_id.as_deref() == Some(item_id.as_str())
|
|
&& approval.outcome.is_some()
|
|
&& !approval.answered_here
|
|
{
|
|
let outcome = if declined {
|
|
"Rifiutato dal Mac"
|
|
} else {
|
|
"Approvato dal Mac"
|
|
};
|
|
if approval.outcome.as_deref() != Some(outcome) {
|
|
approval.outcome = Some(outcome.to_string());
|
|
edits.push(approval.key);
|
|
}
|
|
}
|
|
}
|
|
for key in edits {
|
|
self.edit_approval(key);
|
|
}
|
|
}
|
|
|
|
/// Keeps the latest answered approvals (late message ids and item outcomes still edit
|
|
/// them) and forgets older ones.
|
|
fn prune_approvals(&mut self) {
|
|
let answered = self.approvals.iter().filter(|a| a.outcome.is_some()).count();
|
|
let mut extra = answered.saturating_sub(100);
|
|
self.approvals.retain(|approval| {
|
|
if extra > 0 && approval.outcome.is_some() {
|
|
extra -= 1;
|
|
false
|
|
} else {
|
|
true
|
|
}
|
|
});
|
|
}
|
|
|
|
fn on_turn_completed(&mut self, thread_id: &str, turn: &Turn) {
|
|
let notify = self.settings.notify.turn_end;
|
|
let Some(session) = self.session_mut(thread_id) else {
|
|
return;
|
|
};
|
|
session.busy = false;
|
|
session.active_turn = None;
|
|
session.stream = None;
|
|
let last_message = session.last_message.take();
|
|
let usage = session.usage;
|
|
let reactions = std::mem::take(&mut session.reactions);
|
|
let from_telegram = std::mem::take(&mut session.from_telegram);
|
|
for (chat_id, message_id) in reactions {
|
|
self.post(Outbox::React {
|
|
chat_id,
|
|
message_id,
|
|
emoji: REACTION_DONE,
|
|
});
|
|
}
|
|
self.refresh_session_lists();
|
|
if !notify && !from_telegram {
|
|
return;
|
|
}
|
|
let headline = match turn.status {
|
|
TurnStatus::Completed => None,
|
|
TurnStatus::Interrupted => Some("Turno interrotto."),
|
|
// Errors are reported by their own notification.
|
|
TurnStatus::Failed | TurnStatus::InProgress => return,
|
|
};
|
|
let mut footer = Vec::new();
|
|
if let Some((in_context, output, window)) = usage {
|
|
if let Some(percent) = window.and_then(|w| text::context_used_percent(in_context, w)) {
|
|
footer.push(format!("ctx {percent}%"));
|
|
}
|
|
if let Some(ms) = turn.duration_ms.filter(|ms| *ms > 0)
|
|
&& output > 0
|
|
{
|
|
let rate = output as f64 * 1000.0 / ms as f64;
|
|
footer.push(format!("{rate:.1} t/s"));
|
|
}
|
|
}
|
|
if let Some(ms) = turn.duration_ms.filter(|ms| *ms > 0) {
|
|
footer.push(text::format_duration(ms));
|
|
}
|
|
let footer = footer.join(" · ");
|
|
let mut body = headline.unwrap_or_default().to_string();
|
|
if let Some(answer) = last_message.filter(|answer| !answer.trim().is_empty()) {
|
|
if !body.is_empty() {
|
|
body.push_str("\n\n");
|
|
}
|
|
body.push_str(&text::truncate(answer.trim(), text::SUMMARY_LIMIT));
|
|
}
|
|
if body.is_empty() {
|
|
body.push_str("Turno finito.");
|
|
}
|
|
let mut parts: Vec<Rich> = text::split_message(&body, text::MESSAGE_LIMIT)
|
|
.into_iter()
|
|
.map(Rich::plain)
|
|
.collect();
|
|
if !footer.is_empty() {
|
|
let fits = parts.last().is_some_and(|last| {
|
|
last.text.chars().count() + footer.chars().count() + 2 <= text::MESSAGE_LIMIT
|
|
});
|
|
if fits && let Some(last) = parts.last_mut() {
|
|
last.push("\n\n").push_styled("italic", &footer);
|
|
} else {
|
|
let mut extra = Rich::default();
|
|
extra.push_styled("italic", &footer);
|
|
parts.push(extra);
|
|
}
|
|
}
|
|
for part in parts {
|
|
self.send_session(thread_id, part, None, Tag::Session(thread_id.to_string()));
|
|
}
|
|
}
|
|
|
|
fn on_error(&mut self, error: &ErrorNotification) {
|
|
let message = error.error.message.trim();
|
|
let rate_limited = matches!(
|
|
error.error.codex_error_info,
|
|
Some(CodexErrorInfo::RateLimitExceeded)
|
|
| Some(CodexErrorInfo::HttpConnectionFailed {
|
|
http_status_code: Some(429)
|
|
})
|
|
| Some(CodexErrorInfo::ResponseStreamConnectionFailed {
|
|
http_status_code: Some(429)
|
|
})
|
|
| Some(CodexErrorInfo::ResponseTooManyFailedAttempts {
|
|
http_status_code: Some(429)
|
|
})
|
|
) || message.contains("429");
|
|
let (allowed, headline) = if message.starts_with(LOOP_GUARD_PREFIX) {
|
|
(self.settings.notify.loops, "Protezione dai loop")
|
|
} else if rate_limited {
|
|
(self.settings.notify.errors, "Limite di richieste (429)")
|
|
} else if error.will_retry {
|
|
return;
|
|
} else {
|
|
(self.settings.notify.errors, "Errore")
|
|
};
|
|
if !allowed {
|
|
return;
|
|
}
|
|
let mut rich = Rich::default();
|
|
rich.push_styled("bold", headline)
|
|
.push("\n\n")
|
|
.push(&text::truncate(message, text::MESSAGE_LIMIT - 100));
|
|
self.send_session(&error.thread_id, rich, None, Tag::Session(error.thread_id.clone()));
|
|
}
|
|
|
|
// ---- approvals ---------------------------------------------------------------------
|
|
|
|
fn on_server_request(&mut self, request: ServerRequest) {
|
|
if !self.settings.notify.approvals {
|
|
return;
|
|
}
|
|
let mut rich = Rich::default();
|
|
let (request_id, thread_id, item_id, kind, permissions) = match request {
|
|
ServerRequest::CommandExecutionRequestApproval { request_id, params } => {
|
|
rich.push_styled("bold", "Approvazione richiesta: comando");
|
|
if let Some(command) = ¶ms.command {
|
|
rich.push("\n").push_styled("pre", &text::truncate(command, 1500));
|
|
}
|
|
if let Some(cwd) = ¶ms.cwd {
|
|
rich.push(&format!("\nCartella: {}", cwd.as_str()));
|
|
}
|
|
if let Some(reason) = ¶ms.reason {
|
|
rich.push(&format!("\nMotivo: {}", text::truncate(reason, 500)));
|
|
}
|
|
(
|
|
request_id,
|
|
params.thread_id,
|
|
Some(params.item_id),
|
|
ApprovalKind::Command,
|
|
None,
|
|
)
|
|
}
|
|
ServerRequest::FileChangeRequestApproval { request_id, params } => {
|
|
rich.push_styled("bold", "Approvazione richiesta: modifica dei file");
|
|
if let Some(changes) = self.file_changes.get(¶ms.item_id)
|
|
&& !changes.is_empty()
|
|
{
|
|
let (added, removed) = changes.iter().fold((0, 0), |(a, r), change| {
|
|
let (added, removed) = text::diff_counts(&change.diff);
|
|
(a + added, r + removed)
|
|
});
|
|
rich.push(&format!(
|
|
"\n{} file, +{added} \u{2212}{removed}\n",
|
|
changes.len()
|
|
));
|
|
let mut list = String::new();
|
|
for change in changes.iter().take(30) {
|
|
let (added, removed) = text::diff_counts(&change.diff);
|
|
list.push_str(&format!("{} (+{added} \u{2212}{removed})\n", change.path));
|
|
}
|
|
if changes.len() > 30 {
|
|
list.push_str(&format!("e altri {} file\n", changes.len() - 30));
|
|
}
|
|
rich.push_styled(
|
|
"expandable_blockquote",
|
|
&text::truncate(list.trim_end(), 2500),
|
|
);
|
|
}
|
|
if let Some(reason) = ¶ms.reason {
|
|
rich.push(&format!("\nMotivo: {}", text::truncate(reason, 500)));
|
|
}
|
|
(
|
|
request_id,
|
|
params.thread_id,
|
|
Some(params.item_id),
|
|
ApprovalKind::FileChange,
|
|
None,
|
|
)
|
|
}
|
|
ServerRequest::PermissionsRequestApproval { request_id, params } => {
|
|
rich.push_styled("bold", "Approvazione richiesta: permessi aggiuntivi");
|
|
if let Some(network) = ¶ms.permissions.network {
|
|
rich.push(&format!(
|
|
"\nRete: {}",
|
|
if network.enabled == Some(true) { "sì" } else { "no" }
|
|
));
|
|
}
|
|
if let Some(file_system) = ¶ms.permissions.file_system
|
|
&& let Ok(file_system) = serde_json::to_string(file_system)
|
|
{
|
|
rich.push("\nFile:\n")
|
|
.push_styled("pre", &text::truncate(&file_system, 800));
|
|
}
|
|
if let Some(reason) = ¶ms.reason {
|
|
rich.push(&format!("\nMotivo: {}", text::truncate(reason, 500)));
|
|
}
|
|
(
|
|
request_id,
|
|
params.thread_id,
|
|
None,
|
|
ApprovalKind::Permissions,
|
|
Some(params.permissions),
|
|
)
|
|
}
|
|
_ => return,
|
|
};
|
|
self.next_approval += 1;
|
|
let key = self.next_approval;
|
|
self.approvals.push(Approval {
|
|
key,
|
|
request_id,
|
|
thread_id: thread_id.clone(),
|
|
item_id,
|
|
kind,
|
|
text: rich.clone(),
|
|
permissions,
|
|
messages: Vec::new(),
|
|
outcome: None,
|
|
answered_here: false,
|
|
});
|
|
let mut button = |label: &str, choice: Choice| {
|
|
Button::callback(label, self.register(Action::Approve { key, choice }))
|
|
};
|
|
let buttons = vec![
|
|
vec![
|
|
button("Approva", Choice::Accept).styled("success"),
|
|
button("Approva sempre", Choice::AcceptAlways),
|
|
],
|
|
vec![button("Rifiuta", Choice::Decline).styled("danger")],
|
|
];
|
|
self.send_session(&thread_id, rich, Some(buttons), Tag::Approval(key));
|
|
}
|
|
|
|
fn on_request_resolved(&mut self, request_id: &RequestId) {
|
|
let Some(approval) = self
|
|
.approvals
|
|
.iter_mut()
|
|
.find(|approval| &approval.request_id == request_id)
|
|
else {
|
|
return;
|
|
};
|
|
if approval.outcome.is_some() {
|
|
return;
|
|
}
|
|
// Commands and file changes refine this once their item reports the decision.
|
|
approval.outcome = Some("Risposto dal Mac".to_string());
|
|
let key = approval.key;
|
|
self.edit_approval(key);
|
|
self.prune_approvals();
|
|
}
|
|
|
|
/// Replaces the approval's buttons with a disabled one showing the outcome.
|
|
fn edit_approval(&mut self, key: u64) {
|
|
let Some(approval) = self.approvals.iter().find(|approval| approval.key == key) else {
|
|
return;
|
|
};
|
|
let Some(outcome) = &approval.outcome else {
|
|
return;
|
|
};
|
|
let mut fallback = approval.text.clone();
|
|
fallback.push("\n\n").push_styled("italic", outcome);
|
|
let edits: Vec<Outbox> = approval
|
|
.messages
|
|
.iter()
|
|
.map(|(chat_id, message_id)| Outbox::Edit {
|
|
chat_id: *chat_id,
|
|
message_id: *message_id,
|
|
text: approval.text.clone(),
|
|
buttons: Some(vec![vec![Button::disabled(outcome.clone())]]),
|
|
fallback: Some(fallback.clone()),
|
|
})
|
|
.collect();
|
|
for edit in edits {
|
|
self.post(edit);
|
|
}
|
|
}
|
|
|
|
// ---- Telegram side -------------------------------------------------------------
|
|
|
|
fn post(&self, item: Outbox) {
|
|
if let Some(outbox) = &self.outbox {
|
|
let _ = outbox.send(item);
|
|
}
|
|
}
|
|
|
|
fn register(&mut self, action: Action) -> String {
|
|
let token = format!("k{:016x}", rand::random::<u64>());
|
|
self.callbacks.insert(token.clone(), action);
|
|
self.callback_order.push_back(token.clone());
|
|
while self.callback_order.len() > MAX_CALLBACKS {
|
|
if let Some(old) = self.callback_order.pop_front() {
|
|
self.callbacks.remove(&old);
|
|
}
|
|
}
|
|
token
|
|
}
|
|
|
|
/// Sends a session message to every chat: into its topic, or tagged in the main chat.
|
|
fn send_session(
|
|
&self,
|
|
thread_id: &str,
|
|
text: Rich,
|
|
buttons: Option<Vec<Vec<Button>>>,
|
|
tag: Tag,
|
|
) {
|
|
if self.session(thread_id).is_some() {
|
|
self.ensure_topics(thread_id, true);
|
|
}
|
|
let dest = Dest::Session {
|
|
id: thread_id.to_string(),
|
|
tag: self.tag(thread_id),
|
|
};
|
|
for chat_id in &self.settings.allowed_chat_ids {
|
|
self.post(Outbox::Send {
|
|
chat_id: *chat_id,
|
|
dest: dest.clone(),
|
|
text: text.clone(),
|
|
buttons: buttons.clone(),
|
|
tag: tag.clone(),
|
|
});
|
|
}
|
|
}
|
|
|
|
/// A reply to `origin` (the chat or topic a command came from).
|
|
fn say(&self, origin: Origin, message: &str) {
|
|
self.say_with(origin, Rich::plain(message), None, Tag::None);
|
|
}
|
|
|
|
fn say_with(&self, origin: Origin, text: Rich, buttons: Option<Vec<Vec<Button>>>, tag: Tag) {
|
|
let parts = if text.entities.is_empty() && text.text.chars().count() > text::MESSAGE_LIMIT {
|
|
text::split_message(&text.text, text::MESSAGE_LIMIT)
|
|
.into_iter()
|
|
.map(Rich::plain)
|
|
.collect()
|
|
} else {
|
|
vec![text]
|
|
};
|
|
let count = parts.len();
|
|
for (index, part) in parts.into_iter().enumerate() {
|
|
self.post(Outbox::Send {
|
|
chat_id: origin.chat_id,
|
|
dest: Dest::Chat(origin.thread),
|
|
text: part,
|
|
buttons: if index + 1 == count { buttons.clone() } else { None },
|
|
tag: tag.clone(),
|
|
});
|
|
}
|
|
}
|
|
|
|
/// A session message to one chat.
|
|
fn say_to(&self, chat_id: i64, thread_id: &str, message: &str) {
|
|
self.post(Outbox::Send {
|
|
chat_id,
|
|
dest: Dest::Session {
|
|
id: thread_id.to_string(),
|
|
tag: self.tag(thread_id),
|
|
},
|
|
text: Rich::plain(message),
|
|
buttons: None,
|
|
tag: Tag::Session(thread_id.to_string()),
|
|
});
|
|
}
|
|
|
|
fn answer(&self, callback_id: String, text: &str) {
|
|
self.post(Outbox::Answer {
|
|
callback_id,
|
|
text: text::truncate(text, ANSWER_LIMIT),
|
|
});
|
|
}
|
|
|
|
fn on_sent(&mut self, tag: Tag, chat_id: i64, message_id: i64) {
|
|
match tag {
|
|
Tag::None => {}
|
|
Tag::Session(thread_id) => self.add_route(chat_id, message_id, thread_id),
|
|
Tag::SessionList => {
|
|
let signature = self.session_list_signature();
|
|
self.session_lists.insert(chat_id, (message_id, signature));
|
|
}
|
|
Tag::Plan(thread_id, version) => {
|
|
self.add_route(chat_id, message_id, thread_id.clone());
|
|
let Some(plan) = self
|
|
.session_mut(&thread_id)
|
|
.and_then(|session| session.plan.as_mut())
|
|
else {
|
|
return;
|
|
};
|
|
plan.messages.push((chat_id, message_id));
|
|
if plan.version != version {
|
|
// Updated before the message id was known.
|
|
let text = Rich::plain(plan.text.clone());
|
|
self.post(Outbox::Edit {
|
|
chat_id,
|
|
message_id,
|
|
text,
|
|
buttons: None,
|
|
fallback: None,
|
|
});
|
|
}
|
|
}
|
|
Tag::Approval(key) => {
|
|
let Some(approval) = self.approvals.iter_mut().find(|a| a.key == key) else {
|
|
return;
|
|
};
|
|
approval.messages.push((chat_id, message_id));
|
|
let thread_id = approval.thread_id.clone();
|
|
let answered = approval.outcome.is_some();
|
|
self.add_route(chat_id, message_id, thread_id);
|
|
if answered {
|
|
// Answered before the message id was known.
|
|
self.edit_approval(key);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn add_route(&mut self, chat_id: i64, message_id: i64, thread_id: String) {
|
|
self.routes.push_back(((chat_id, message_id), thread_id));
|
|
while self.routes.len() > MAX_ROUTES {
|
|
self.routes.pop_front();
|
|
}
|
|
}
|
|
|
|
fn on_update(&mut self, update: Update) {
|
|
let Some(chat_id) = update.chat_id() else {
|
|
return;
|
|
};
|
|
if !self.settings.is_allowed(chat_id) {
|
|
// Unknown chats get no answer, except the pending pairing code.
|
|
if let Some(text) = update.message.as_ref().and_then(|m| m.text.as_deref()) {
|
|
match pairing::try_pair(&self.options.codex_home, chat_id, text) {
|
|
Ok(true) => {
|
|
self.settings = TelegramSettings::load(&self.options.codex_home);
|
|
let origin = Origin {
|
|
chat_id,
|
|
thread: None,
|
|
};
|
|
self.say(origin, pairing::PAIRED_REPLY);
|
|
}
|
|
Ok(false) => {}
|
|
Err(err) => warn!("telegram: cannot save the paired chat: {err}"),
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
if let Some(query) = update.callback_query {
|
|
// In a private chat only its user may press the buttons.
|
|
let presser_ok = query
|
|
.from
|
|
.as_ref()
|
|
.is_none_or(|from| chat_id < 0 || from.id == chat_id);
|
|
if presser_ok {
|
|
self.on_callback(chat_id, query);
|
|
}
|
|
return;
|
|
}
|
|
if let Some(stopped) = update.stopped_message_generation {
|
|
self.on_draft_stopped(chat_id, stopped.draft_id);
|
|
return;
|
|
}
|
|
if let Some(message) = update.message {
|
|
self.on_message(chat_id, message, false);
|
|
} else if let Some(message) = update.edited_message {
|
|
self.on_message(chat_id, message, true);
|
|
}
|
|
}
|
|
|
|
fn on_draft_stopped(&mut self, chat_id: i64, draft_id: i64) {
|
|
let Some(session) = self.sessions.iter_mut().find(|session| {
|
|
session
|
|
.stream
|
|
.as_ref()
|
|
.is_some_and(|stream| stream.draft_id == draft_id)
|
|
}) else {
|
|
return;
|
|
};
|
|
if let Some(stream) = session.stream.as_mut() {
|
|
stream.stopped = true;
|
|
}
|
|
let thread_id = session.thread_id.clone();
|
|
self.interrupt(&thread_id, Some(chat_id));
|
|
}
|
|
|
|
/// Interrupts the running turn; `false` when none runs.
|
|
fn interrupt(&mut self, thread_id: &str, reply_chat: Option<i64>) -> bool {
|
|
let Some(turn_id) = self
|
|
.session(thread_id)
|
|
.and_then(|session| session.active_turn.clone())
|
|
else {
|
|
return false;
|
|
};
|
|
let thread = thread_id.to_string();
|
|
self.request(
|
|
|request_id| ClientRequest::TurnInterrupt {
|
|
request_id,
|
|
params: TurnInterruptParams {
|
|
thread_id: thread,
|
|
turn_id,
|
|
},
|
|
},
|
|
Pending::Interrupt {
|
|
chat_id: reply_chat,
|
|
thread_id: thread_id.to_string(),
|
|
},
|
|
);
|
|
true
|
|
}
|
|
|
|
fn on_callback(&mut self, chat_id: i64, query: CallbackQuery) {
|
|
let CallbackQuery {
|
|
id: callback_id,
|
|
message,
|
|
data,
|
|
..
|
|
} = query;
|
|
let Some(action) = data.and_then(|data| self.callbacks.get(&data).cloned()) else {
|
|
self.answer(callback_id, "Pulsante scaduto: ripeti il comando.");
|
|
return;
|
|
};
|
|
let origin = Origin {
|
|
chat_id,
|
|
thread: message.as_ref().and_then(Message::topic),
|
|
};
|
|
let message_id = message.as_ref().map(|message| message.message_id);
|
|
match action {
|
|
Action::Approve { key, choice } => self.on_approval_choice(callback_id, key, choice),
|
|
Action::Stop(thread_id) => {
|
|
let text = if self.session(&thread_id).is_none() {
|
|
"Sessione chiusa."
|
|
} else if self.interrupt(&thread_id, None) {
|
|
"Interruzione richiesta."
|
|
} else {
|
|
"Nessun turno in corso."
|
|
};
|
|
self.answer(callback_id, text);
|
|
}
|
|
Action::Status(thread_id) => {
|
|
let text = self.status_text(&thread_id);
|
|
self.answer(callback_id, &text);
|
|
}
|
|
Action::RefreshSessions => {
|
|
self.answer(callback_id, "Aggiornato.");
|
|
if let Some(message_id) = message_id {
|
|
let (text, buttons) = self.session_list();
|
|
let signature = self.session_list_signature();
|
|
self.session_lists.insert(chat_id, (message_id, signature));
|
|
self.post(Outbox::Edit {
|
|
chat_id,
|
|
message_id,
|
|
text,
|
|
buttons: Some(buttons),
|
|
fallback: None,
|
|
});
|
|
}
|
|
}
|
|
Action::NewSessionMenu => {
|
|
self.answer(callback_id, "");
|
|
self.new_session_menu(origin, None);
|
|
}
|
|
Action::NewSession(cwd) => {
|
|
self.answer(callback_id, "Avvio la sessione.");
|
|
self.request(
|
|
|request_id| ClientRequest::ThreadStart {
|
|
request_id,
|
|
params: ThreadStartParams {
|
|
cwd: Some(cwd),
|
|
..Default::default()
|
|
},
|
|
},
|
|
Pending::NewThread {
|
|
chat_id,
|
|
thread: origin.thread,
|
|
adopt: None,
|
|
},
|
|
);
|
|
}
|
|
Action::SendTo { pending, thread_id } => {
|
|
let Some(text) = self.pending_texts.remove(&pending) else {
|
|
self.answer(callback_id, "Messaggio già inviato.");
|
|
return;
|
|
};
|
|
if self.session(&thread_id).is_none() {
|
|
self.answer(callback_id, "Sessione chiusa.");
|
|
return;
|
|
}
|
|
let name = self.topic_name(&thread_id);
|
|
self.answer(callback_id, &format!("Inviato a {name}."));
|
|
self.add_route(text.chat_id, text.message_id, thread_id.clone());
|
|
self.send_user_text(text.chat_id, &thread_id, text.text, Some(text.message_id));
|
|
}
|
|
Action::Adopt {
|
|
pending,
|
|
thread_id,
|
|
cwd,
|
|
} => {
|
|
let Some(text) = self.pending_texts.remove(&pending) else {
|
|
self.answer(callback_id, "Messaggio già inviato.");
|
|
return;
|
|
};
|
|
match (thread_id, cwd) {
|
|
(Some(thread_id), _) => {
|
|
if self.session(&thread_id).is_none() {
|
|
self.pending_texts.insert(pending, text);
|
|
self.answer(callback_id, "Sessione chiusa.");
|
|
return;
|
|
}
|
|
let name = self.topic_name(&thread_id);
|
|
self.answer(callback_id, &format!("Inviato a {name}."));
|
|
self.adopt_topic(text, &thread_id);
|
|
}
|
|
(None, cwd) => {
|
|
self.answer(callback_id, "Avvio la sessione.");
|
|
self.request(
|
|
|request_id| ClientRequest::ThreadStart {
|
|
request_id,
|
|
params: ThreadStartParams {
|
|
cwd,
|
|
..Default::default()
|
|
},
|
|
},
|
|
Pending::NewThread {
|
|
chat_id,
|
|
thread: origin.thread,
|
|
adopt: Some(text),
|
|
},
|
|
);
|
|
}
|
|
}
|
|
}
|
|
Action::Toggle(toggle) => {
|
|
let value = !toggle.get(&self.settings);
|
|
if let Err(err) = set_toggle(&self.options.codex_home, toggle, value) {
|
|
warn!("telegram: cannot save a setting: {err}");
|
|
self.answer(callback_id, "Impostazione non salvata.");
|
|
return;
|
|
}
|
|
self.settings = TelegramSettings::load(&self.options.codex_home);
|
|
self.answer(
|
|
callback_id,
|
|
&format!("{}: {}", toggle.label(), yes_no(toggle.get(&self.settings))),
|
|
);
|
|
if let Some(message_id) = message_id {
|
|
let (text, buttons) = self.settings_message();
|
|
self.post(Outbox::Edit {
|
|
chat_id,
|
|
message_id,
|
|
text,
|
|
buttons: Some(buttons),
|
|
fallback: None,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn on_approval_choice(&mut self, callback_id: String, key: u64, choice: Choice) {
|
|
let Some(approval) = self.approvals.iter_mut().find(|a| a.key == key) else {
|
|
self.answer(callback_id, "Richiesta non più attiva.");
|
|
return;
|
|
};
|
|
if approval.outcome.is_some() {
|
|
self.answer(callback_id, "Già risolta.");
|
|
return;
|
|
}
|
|
let (result, outcome) = approval_response(approval, choice);
|
|
let Some(result) = result else {
|
|
return;
|
|
};
|
|
approval.outcome = Some(outcome.to_string());
|
|
approval.answered_here = true;
|
|
let request_id = approval.request_id.clone();
|
|
self.send_to_server(JSONRPCMessage::Response(JSONRPCResponse {
|
|
id: request_id,
|
|
result,
|
|
}));
|
|
self.answer(callback_id, outcome);
|
|
self.edit_approval(key);
|
|
self.prune_approvals();
|
|
}
|
|
|
|
fn on_message(&mut self, chat_id: i64, message: Message, edited: bool) {
|
|
let Some(body) = message.text.clone().filter(|text| !text.trim().is_empty()) else {
|
|
return;
|
|
};
|
|
let trimmed = body.trim();
|
|
let is_command = trimmed.starts_with('/');
|
|
// An edited command runs again; edits of plain text are ignored.
|
|
if edited && !is_command {
|
|
return;
|
|
}
|
|
let topic = message.topic();
|
|
let origin = Origin {
|
|
chat_id,
|
|
thread: topic,
|
|
};
|
|
let topic_session = topic.and_then(|thread| {
|
|
self.lock_topics()
|
|
.session_for(chat_id, thread)
|
|
.map(ToString::to_string)
|
|
});
|
|
let replied = message.reply_to_message.as_ref().and_then(|replied| {
|
|
self.routes
|
|
.iter()
|
|
.rev()
|
|
.find(|((chat, id), _)| *chat == chat_id && *id == replied.message_id)
|
|
.map(|(_, thread_id)| thread_id.clone())
|
|
});
|
|
if let Some(stray) = topic.filter(|_| topic_session.is_none() && replied.is_none()) {
|
|
self.on_stray_topic(chat_id, stray, message.message_id, trimmed, body.clone());
|
|
return;
|
|
}
|
|
let target = topic_session.or(replied);
|
|
if is_command {
|
|
let target = target.filter(|thread_id| self.session(thread_id).is_some());
|
|
self.on_command(origin, trimmed, target);
|
|
return;
|
|
}
|
|
match target {
|
|
Some(thread_id) if self.session(&thread_id).is_some() => {
|
|
self.send_user_text(chat_id, &thread_id, body, Some(message.message_id));
|
|
}
|
|
Some(_) => self.say(
|
|
origin,
|
|
"Questa sessione è chiusa. Usa /sessioni per vedere quelle attive o /nuova per avviarne una.",
|
|
),
|
|
None => match self.sessions.as_slice() {
|
|
[] => self.say(origin, "Nessuna sessione di aKode attiva. Usa /nuova per avviarne una."),
|
|
[only] => {
|
|
let thread_id = only.thread_id.clone();
|
|
self.send_user_text(chat_id, &thread_id, body, Some(message.message_id));
|
|
}
|
|
_ => self.choose_session_for(origin, message.message_id, body),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn store_pending(&mut self, text: PendingText) -> u64 {
|
|
self.next_pending_text += 1;
|
|
let pending = self.next_pending_text;
|
|
self.pending_texts.insert(pending, text);
|
|
while self.pending_texts.len() > 50 {
|
|
let Some(oldest) = self.pending_texts.keys().min().copied() else {
|
|
break;
|
|
};
|
|
self.pending_texts.remove(&oldest);
|
|
}
|
|
pending
|
|
}
|
|
|
|
/// A message in a topic that belongs to no session: the user made it with «Nuova chat»,
|
|
/// and Telegram named it after the text. A command is answered in the main chat and the
|
|
/// topic deleted; plain text asks which session the topic is for.
|
|
fn on_stray_topic(&mut self, chat_id: i64, topic: i64, message_id: i64, trimmed: &str, body: String) {
|
|
if trimmed.starts_with('/') {
|
|
let origin = Origin {
|
|
chat_id,
|
|
thread: None,
|
|
};
|
|
self.on_command(origin, trimmed, None);
|
|
self.post(Outbox::DeleteTopic {
|
|
chat_id,
|
|
thread: topic,
|
|
session: None,
|
|
fallback_name: None,
|
|
});
|
|
return;
|
|
}
|
|
let pending = self.store_pending(PendingText {
|
|
chat_id,
|
|
message_id,
|
|
text: body,
|
|
topic: Some(topic),
|
|
});
|
|
let threads: Vec<String> = self.sessions.iter().map(|s| s.thread_id.clone()).collect();
|
|
let mut rows = Vec::new();
|
|
for thread_id in threads {
|
|
let label = self.topic_name(&thread_id);
|
|
let token = self.register(Action::Adopt {
|
|
pending,
|
|
thread_id: Some(thread_id),
|
|
cwd: None,
|
|
});
|
|
rows.push(vec![Button::callback(label, token)]);
|
|
}
|
|
let cwd = self
|
|
.lock_topics()
|
|
.recent_cwds()
|
|
.first()
|
|
.cloned()
|
|
.or_else(|| self.sessions.last().map(|s| s.cwd.display().to_string()));
|
|
if let Some(cwd) = cwd {
|
|
let token = self.register(Action::Adopt {
|
|
pending,
|
|
thread_id: None,
|
|
cwd: Some(cwd),
|
|
});
|
|
rows.push(vec![Button::callback("Nuova sessione", token)]);
|
|
}
|
|
let origin = Origin {
|
|
chat_id,
|
|
thread: Some(topic),
|
|
};
|
|
if rows.is_empty() {
|
|
self.say(origin, "Nessuna sessione di aKode attiva. Avvia una sessione dal Mac.");
|
|
return;
|
|
}
|
|
self.say_with(
|
|
origin,
|
|
Rich::plain("A quale sessione appartiene questo topic?"),
|
|
Some(rows),
|
|
Tag::None,
|
|
);
|
|
}
|
|
|
|
/// Maps the topic of `text` to `thread_id` and sends the text there. When the session
|
|
/// already has its own topic, the text goes to it and the extra topic is deleted.
|
|
fn adopt_topic(&mut self, text: PendingText, thread_id: &str) {
|
|
let Some(topic) = text.topic else {
|
|
return;
|
|
};
|
|
let existing = self
|
|
.lock_topics()
|
|
.entry(text.chat_id, thread_id)
|
|
.map(|entry| entry.thread)
|
|
.filter(|thread| *thread != topic);
|
|
if existing.is_some() {
|
|
self.post(Outbox::DeleteTopic {
|
|
chat_id: text.chat_id,
|
|
thread: topic,
|
|
session: None,
|
|
fallback_name: None,
|
|
});
|
|
self.send_user_text(text.chat_id, thread_id, text.text, None);
|
|
return;
|
|
}
|
|
self.lock_topics().insert(TopicEntry {
|
|
chat_id: text.chat_id,
|
|
session: thread_id.to_string(),
|
|
thread: topic,
|
|
name: String::new(),
|
|
pending_name: None,
|
|
});
|
|
self.post(Outbox::Topic {
|
|
chat_id: text.chat_id,
|
|
session: thread_id.to_string(),
|
|
name: self.topic_name(thread_id),
|
|
create: false,
|
|
});
|
|
self.add_route(text.chat_id, text.message_id, thread_id.to_string());
|
|
self.send_user_text(text.chat_id, thread_id, text.text, Some(text.message_id));
|
|
}
|
|
|
|
/// Several sessions and no topic: asks with buttons where the message goes.
|
|
fn choose_session_for(&mut self, origin: Origin, message_id: i64, text: String) {
|
|
let pending = self.store_pending(PendingText {
|
|
chat_id: origin.chat_id,
|
|
message_id,
|
|
text,
|
|
topic: None,
|
|
});
|
|
let threads: Vec<String> = self.sessions.iter().map(|s| s.thread_id.clone()).collect();
|
|
let mut rows = Vec::new();
|
|
for thread_id in threads {
|
|
let label = self.topic_name(&thread_id);
|
|
let token = self.register(Action::SendTo { pending, thread_id });
|
|
rows.push(vec![Button::callback(label, token)]);
|
|
}
|
|
self.say_with(
|
|
origin,
|
|
Rich::plain("Più sessioni attive: a quale invio il messaggio?"),
|
|
Some(rows),
|
|
Tag::None,
|
|
);
|
|
}
|
|
|
|
fn send_user_text(&mut self, chat_id: i64, thread_id: &str, text: String, message_id: Option<i64>) {
|
|
let Some(session) = self.session(thread_id) else {
|
|
return;
|
|
};
|
|
let thread = thread_id.to_string();
|
|
if let Some(turn_id) = session.active_turn.clone() {
|
|
let input = user_input(text.clone());
|
|
self.request(
|
|
|request_id| ClientRequest::TurnSteer {
|
|
request_id,
|
|
params: TurnSteerParams {
|
|
thread_id: thread.clone(),
|
|
input,
|
|
expected_turn_id: turn_id,
|
|
..Default::default()
|
|
},
|
|
},
|
|
Pending::Steer {
|
|
chat_id,
|
|
thread_id: thread_id.to_string(),
|
|
text,
|
|
message_id,
|
|
},
|
|
);
|
|
} else {
|
|
self.request(
|
|
|request_id| ClientRequest::TurnStart {
|
|
request_id,
|
|
params: TurnStartParams {
|
|
thread_id: thread,
|
|
input: user_input(text),
|
|
..Default::default()
|
|
},
|
|
},
|
|
Pending::Start {
|
|
chat_id,
|
|
thread_id: thread_id.to_string(),
|
|
message_id,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
fn on_command(&mut self, origin: Origin, command: &str, target: Option<String>) {
|
|
let name = command
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or_default()
|
|
.split('@')
|
|
.next()
|
|
.unwrap_or_default();
|
|
let single = match self.sessions.as_slice() {
|
|
[only] => Some(only.thread_id.clone()),
|
|
_ => None,
|
|
};
|
|
match name {
|
|
"/sessioni" => {
|
|
let (text, buttons) = self.session_list();
|
|
self.say_with(origin, text, Some(buttons), Tag::SessionList);
|
|
}
|
|
"/nuova" => self.new_session_menu(origin, target),
|
|
"/stato" => match target.or(single) {
|
|
Some(thread_id) => {
|
|
let text = self.status_text(&thread_id);
|
|
self.say(origin, &text);
|
|
}
|
|
None => {
|
|
let (text, buttons) = self.session_list();
|
|
self.say_with(origin, text, Some(buttons), Tag::SessionList);
|
|
}
|
|
},
|
|
"/stop" => match target.or(single) {
|
|
Some(thread_id) => {
|
|
if !self.interrupt(&thread_id, Some(origin.chat_id)) {
|
|
self.say_to(origin.chat_id, &thread_id, "Nessun turno in corso.");
|
|
}
|
|
}
|
|
None if self.sessions.is_empty() => {
|
|
self.say(origin, "Nessuna sessione di aKode attiva.");
|
|
}
|
|
None => {
|
|
let (text, buttons) = self.session_list();
|
|
self.say_with(origin, text, Some(buttons), Tag::SessionList);
|
|
}
|
|
},
|
|
"/impostazioni" => {
|
|
let (text, buttons) = self.settings_message();
|
|
self.say_with(origin, text, Some(buttons), Tag::None);
|
|
}
|
|
_ => {
|
|
let text = self.help_text();
|
|
self.say(origin, &text);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn help_text(&self) -> String {
|
|
let mut text = String::from(
|
|
"aKode su Telegram\n\n\
|
|
/sessioni elenca le sessioni, con i pulsanti Apri, Stato e Stop\n\
|
|
/nuova avvia una nuova sessione in una cartella recente\n\
|
|
/stato mostra lo stato della sessione\n\
|
|
/stop interrompe il turno in corso\n\
|
|
/impostazioni sceglie notifiche, streaming e reazioni\n\
|
|
/aiuto mostra questa guida\n\n",
|
|
);
|
|
if self.topics_enabled() {
|
|
text.push_str(
|
|
"Ogni sessione ha il suo topic dal primo turno: scrivi nel topic per parlare con \
|
|
quella sessione. Nella chat principale rispondi a un messaggio della sessione. \
|
|
In una nuova chat di Telegram ti chiedo a quale sessione appartiene.",
|
|
);
|
|
} else {
|
|
text.push_str(
|
|
"I topic non sono attivi per questo bot: i messaggi arrivano qui con il prefisso \
|
|
[cartella · modello] e, con più sessioni, scegli la sessione con i pulsanti.\n\n\
|
|
Per avere un topic per sessione: apri @BotFather, scegli il bot, poi \
|
|
Bot Settings e attiva Threaded Mode (i topic nelle chat private). \
|
|
aKode se ne accorge da solo entro qualche minuto.",
|
|
);
|
|
}
|
|
text
|
|
}
|
|
|
|
fn settings_message(&mut self) -> (Rich, Vec<Vec<Button>>) {
|
|
let mut rich = Rich::default();
|
|
rich.push_styled("bold", "Impostazioni di Telegram")
|
|
.push("\nNotifiche: approvazioni, fine turno, errori e loop. Tocca un'opzione per cambiarla.");
|
|
let mut rows = Vec::new();
|
|
for toggle in Toggle::ALL {
|
|
let label = format!("{}: {}", toggle.label(), yes_no(toggle.get(&self.settings)));
|
|
let token = self.register(Action::Toggle(toggle));
|
|
rows.push(vec![Button::callback(label, token)]);
|
|
}
|
|
(rich, rows)
|
|
}
|
|
|
|
fn new_session_menu(&mut self, origin: Origin, target: Option<String>) {
|
|
let mut cwds: Vec<String> = Vec::new();
|
|
let mut add = |cwd: String| {
|
|
if !cwds.contains(&cwd) {
|
|
cwds.push(cwd);
|
|
}
|
|
};
|
|
if let Some(session) = target.as_deref().and_then(|t| self.session(t)) {
|
|
add(session.cwd.display().to_string());
|
|
}
|
|
for cwd in self.lock_topics().recent_cwds() {
|
|
add(cwd.clone());
|
|
}
|
|
for session in &self.sessions {
|
|
add(session.cwd.display().to_string());
|
|
}
|
|
cwds.truncate(8);
|
|
if cwds.is_empty() {
|
|
self.say(
|
|
origin,
|
|
"Nessuna cartella recente: avvia una sessione dal Mac, poi potrai crearne altre da qui.",
|
|
);
|
|
return;
|
|
}
|
|
let mut text = String::from("Nuova sessione: in quale cartella?");
|
|
let mut rows = Vec::new();
|
|
for (index, cwd) in cwds.into_iter().enumerate() {
|
|
text.push_str(&format!("\n{}. {cwd}", index + 1));
|
|
let base = std::path::Path::new(&cwd)
|
|
.file_name()
|
|
.and_then(|name| name.to_str())
|
|
.unwrap_or("/")
|
|
.to_string();
|
|
let token = self.register(Action::NewSession(cwd));
|
|
rows.push(vec![Button::callback(
|
|
format!("{}. {}", index + 1, text::truncate(&base, 40)),
|
|
token,
|
|
)]);
|
|
}
|
|
self.say_with(origin, Rich::plain(text), Some(rows), Tag::None);
|
|
}
|
|
|
|
fn session_line(&self, session: &Session) -> String {
|
|
let mut line = if session.busy { "al lavoro" } else { "libera" }.to_string();
|
|
if let Some((in_context, _, Some(window))) = session.usage
|
|
&& let Some(percent) = text::context_used_percent(in_context, window)
|
|
{
|
|
line.push_str(&format!(" · ctx {percent}%"));
|
|
}
|
|
let waiting = self
|
|
.approvals
|
|
.iter()
|
|
.filter(|a| a.thread_id == session.thread_id && a.outcome.is_none())
|
|
.count();
|
|
match waiting {
|
|
0 => {}
|
|
1 => line.push_str(" · 1 approvazione in attesa"),
|
|
n => line.push_str(&format!(" · {n} approvazioni in attesa")),
|
|
}
|
|
line
|
|
}
|
|
|
|
fn topic_link(&self, chat_id: i64, thread_id: &str) -> Option<String> {
|
|
let topics = self.lock_topics();
|
|
let thread = topics.thread_for(chat_id, thread_id)?;
|
|
let username = topics.bot_username.as_deref()?;
|
|
Some(format!("https://t.me/{username}/{thread}"))
|
|
}
|
|
|
|
/// What the session list shows; it changes only when this does.
|
|
fn session_list_signature(&self) -> String {
|
|
self.sessions
|
|
.iter()
|
|
.map(|session| {
|
|
format!(
|
|
"{}|{}|{}",
|
|
self.topic_name(&session.thread_id),
|
|
self.session_line(session),
|
|
self.settings
|
|
.allowed_chat_ids
|
|
.iter()
|
|
.any(|chat| self.topic_link(*chat, &session.thread_id).is_some())
|
|
)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
}
|
|
|
|
fn session_list(&mut self) -> (Rich, Vec<Vec<Button>>) {
|
|
let mut rich = Rich::default();
|
|
let mut rows = Vec::new();
|
|
if self.sessions.is_empty() {
|
|
rich.push("Nessuna sessione di aKode attiva.");
|
|
} else {
|
|
rich.push_styled("bold", &format!("Sessioni attive ({})", self.sessions.len()));
|
|
let entries: Vec<(String, String, String)> = self
|
|
.sessions
|
|
.iter()
|
|
.map(|session| {
|
|
(
|
|
session.thread_id.clone(),
|
|
self.topic_name(&session.thread_id),
|
|
self.session_line(session),
|
|
)
|
|
})
|
|
.collect();
|
|
let chat = self.settings.allowed_chat_ids.first().copied().unwrap_or_default();
|
|
for (index, (thread_id, name, line)) in entries.into_iter().enumerate() {
|
|
let number = index + 1;
|
|
rich.push(&format!("\n\n{number}. {name}\n{line}"));
|
|
let mut row = Vec::new();
|
|
if let Some(link) = self.topic_link(chat, &thread_id) {
|
|
row.push(Button::link(format!("{number} · Apri"), link).styled("primary"));
|
|
}
|
|
row.push(Button::callback(
|
|
format!("{number} · Stato"),
|
|
self.register(Action::Status(thread_id.clone())),
|
|
));
|
|
row.push(
|
|
Button::callback(format!("{number} · Stop"), self.register(Action::Stop(thread_id)))
|
|
.styled("danger"),
|
|
);
|
|
rows.push(row);
|
|
}
|
|
}
|
|
rows.push(vec![
|
|
Button::callback("Aggiorna", self.register(Action::RefreshSessions)),
|
|
Button::callback("Nuova sessione", self.register(Action::NewSessionMenu)),
|
|
]);
|
|
(rich, rows)
|
|
}
|
|
|
|
/// Edits the latest `/sessioni` message of each chat when what it shows changed.
|
|
fn refresh_session_lists(&mut self) {
|
|
if self.session_lists.is_empty() {
|
|
return;
|
|
}
|
|
let signature = self.session_list_signature();
|
|
let stale: Vec<(i64, i64)> = self
|
|
.session_lists
|
|
.iter()
|
|
.filter(|(_, (_, shown))| *shown != signature)
|
|
.map(|(chat, (message_id, _))| (*chat, *message_id))
|
|
.collect();
|
|
for (chat_id, message_id) in stale {
|
|
let (text, buttons) = self.session_list();
|
|
self.session_lists
|
|
.insert(chat_id, (message_id, signature.clone()));
|
|
self.post(Outbox::Edit {
|
|
chat_id,
|
|
message_id,
|
|
text,
|
|
buttons: Some(buttons),
|
|
fallback: None,
|
|
});
|
|
}
|
|
}
|
|
|
|
fn status_text(&self, thread_id: &str) -> String {
|
|
let Some(session) = self.session(thread_id) else {
|
|
return "Sessione chiusa.".to_string();
|
|
};
|
|
format!(
|
|
"{} · {}\nModalità: {}\nCartella: {}",
|
|
self.topic_name(thread_id),
|
|
self.session_line(session),
|
|
session.mode,
|
|
session.cwd.display()
|
|
)
|
|
}
|
|
}
|
|
|
|
/// The end of the running answer, as shown in a draft.
|
|
const MODE_DEFAULT: &str = "default";
|
|
|
|
/// The session mode as the TUI shows it: plan, full access (no sandbox) or default.
|
|
fn session_mode(mode: Option<serde_json::Value>, sandbox: &impl serde::Serialize) -> &'static str {
|
|
let plan = mode.is_some_and(|mode| mode == "plan");
|
|
let full = serde_json::to_value(sandbox)
|
|
.ok()
|
|
.is_some_and(|sandbox| sandbox["type"] == "dangerFullAccess");
|
|
if plan {
|
|
"plan"
|
|
} else if full {
|
|
"accesso completo"
|
|
} else {
|
|
MODE_DEFAULT
|
|
}
|
|
}
|
|
|
|
/// «… (chiusa)», once.
|
|
fn closed_name(name: &str) -> String {
|
|
if name.ends_with("(chiusa)") {
|
|
name.to_string()
|
|
} else {
|
|
text::closed_topic_name(name)
|
|
}
|
|
}
|
|
|
|
fn draft_tail(text: &str) -> String {
|
|
let count = text.chars().count();
|
|
if count <= DRAFT_TAIL {
|
|
return text.to_string();
|
|
}
|
|
let tail: String = text.chars().skip(count - DRAFT_TAIL).collect();
|
|
format!("…{tail}")
|
|
}
|
|
|
|
fn user_input(text: String) -> Vec<UserInput> {
|
|
vec![UserInput::Text {
|
|
text,
|
|
text_elements: Vec::new(),
|
|
}]
|
|
}
|
|
|
|
/// The JSON-RPC result for `choice` and the outcome shown on the request.
|
|
fn approval_response(approval: &Approval, choice: Choice) -> (Option<serde_json::Value>, &'static str) {
|
|
let outcome = match choice {
|
|
Choice::Accept => "Approvato da Telegram",
|
|
Choice::AcceptAlways => "Approvato sempre da Telegram",
|
|
Choice::Decline => "Rifiutato da Telegram",
|
|
};
|
|
let value = match approval.kind {
|
|
ApprovalKind::Command => serde_json::to_value(CommandExecutionRequestApprovalResponse {
|
|
decision: match choice {
|
|
Choice::Accept => CommandExecutionApprovalDecision::Accept,
|
|
Choice::AcceptAlways => CommandExecutionApprovalDecision::AcceptForSession,
|
|
Choice::Decline => CommandExecutionApprovalDecision::Decline,
|
|
},
|
|
}),
|
|
ApprovalKind::FileChange => serde_json::to_value(FileChangeRequestApprovalResponse {
|
|
decision: match choice {
|
|
Choice::Accept => FileChangeApprovalDecision::Accept,
|
|
Choice::AcceptAlways => FileChangeApprovalDecision::AcceptForSession,
|
|
Choice::Decline => FileChangeApprovalDecision::Decline,
|
|
},
|
|
}),
|
|
ApprovalKind::Permissions => {
|
|
let granted = match (choice, approval.permissions.clone()) {
|
|
(Choice::Accept | Choice::AcceptAlways, Some(requested)) => {
|
|
GrantedPermissionProfile {
|
|
network: requested.network,
|
|
file_system: requested.file_system,
|
|
}
|
|
}
|
|
_ => GrantedPermissionProfile {
|
|
network: None,
|
|
file_system: None,
|
|
},
|
|
};
|
|
serde_json::to_value(PermissionsRequestApprovalResponse {
|
|
permissions: granted,
|
|
scope: if choice == Choice::AcceptAlways {
|
|
PermissionGrantScope::Session
|
|
} else {
|
|
PermissionGrantScope::Turn
|
|
},
|
|
strict_auto_review: None,
|
|
})
|
|
}
|
|
};
|
|
(value.ok(), outcome)
|
|
}
|
|
|
|
/// Long-polls `getUpdates`, backing off on errors; ends with an error only when the token
|
|
/// is refused.
|
|
async fn run_poller(
|
|
api: TelegramApi,
|
|
timeout_secs: u64,
|
|
updates: mpsc::Sender<Result<Vec<Update>, ApiError>>,
|
|
) {
|
|
let mut offset = None;
|
|
let mut backoff = Duration::from_secs(1);
|
|
loop {
|
|
match api.get_updates(offset, timeout_secs).await {
|
|
Ok(batch) => {
|
|
backoff = Duration::from_secs(1);
|
|
if let Some(last) = batch.last() {
|
|
offset = Some(last.update_id + 1);
|
|
}
|
|
if !batch.is_empty() && updates.send(Ok(batch)).await.is_err() {
|
|
return;
|
|
}
|
|
}
|
|
Err(err) if err.is_unauthorized() => {
|
|
let _ = updates.send(Err(err)).await;
|
|
return;
|
|
}
|
|
Err(err) => {
|
|
let wait = err
|
|
.retry_after()
|
|
.map(Duration::from_secs)
|
|
.unwrap_or(backoff);
|
|
warn!("telegram: getUpdates failed, retrying in {}s: {err}", wait.as_secs());
|
|
tokio::time::sleep(wait).await;
|
|
backoff = (backoff * 2).min(Duration::from_secs(60));
|
|
}
|
|
}
|
|
}
|
|
}
|