Download dev/code_chi11321__CrabPort.txt from ag2003/length-extrapolating-architecture-data: direct link, hf CLI and curl.
- Browser
- Download file 115 kB
-
https://huggingface.co/datasets/ag2003/length-extrapolating-architecture-data/resolve/main/dev/code_chi11321__CrabPort.txt
- Command line
-
hf download hf://datasets/ag2003/length-extrapolating-architecture-data/dev/code_chi11321__CrabPort.txt
-
curl -L -o code_chi11321__CrabPort.txt https://huggingface.co/datasets/ag2003/length-extrapolating-architecture-data/resolve/main/dev/code_chi11321__CrabPort.txt
115 kB
# ===== file: build.rs =====
//! Build script for the main `CrabPort` binary.
//!
//! On Windows, embeds `app-icon.ico` into the final `.exe` so the OS shows
//! our icon in the taskbar, Alt-Tab switcher, and Explorer (instead of the
//! generic Rust exe icon). The icon is referenced from a tiny `.rc` resource
//! script compiled by `embed-resource`, which finds `rc.exe` from the Windows
//! SDK / MSVC toolchain automatically.
//!
//! On macOS and Linux this is a no-op — the platform bundles (`.app` /
//! `.AppImage`) carry the icon via `cargo-bundle` using
//! `[package.metadata.bundle].icon`, not via the binary itself.
//!
//! No version-sync check is needed here: `[workspace.package].version` is the
//! single source of truth, inherited by every member crate via
//! `version.workspace = true`. `cargo-bundle` reads the package version via
//! `cargo_metadata` (which resolves workspace inheritance), and since we
//! intentionally do NOT set `bundle.version`, it falls back to the package
//! version automatically — no duplication to drift out of sync.
#[cfg(target_os = "windows")]
fn main() {
// Re-run if the icon or rc file changes.
println!("cargo:rerun-if-changed=app-icon.ico");
println!("cargo:rerun-if-changed=crabport.rc");
embed_resource::compile("crabport.rc", embed_resource::NONE)
.manifest_optional()
.expect("failed to compile crabport.rc");
}
#[cfg(not(target_os = "windows"))]
fn main() {
// Re-run if the macOS Info.plist extension changes — it's merged
// into the generated Info.plist by `cargo-bundle`, but `cargo-bundle`
// runs outside of cargo's dependency tracking so we have to opt in.
println!("cargo:rerun-if-changed=Info.plist.ext");
}
# ===== file: crabport-agent/src/agent.rs =====
//! The agent's tool execution: one [`Agent`] per conversation runs the
//! advertised tools against an [`AgentSession`].
//!
//! Everything here is UI-free — the polling loops included. They run on
//! background threads via `smol`, and hand their result to the UI through an
//! [`Executed::Pending`] receiver; the UI only awaits and renders.
use std::sync::{Arc, Mutex};
use std::time::Instant;
use async_channel::{Receiver, bounded};
use rust_i18n::t;
use serde_json::Value;
use crabport_ssh::{TOKIO, TunnelKind, TunnelManager, TunnelStatus};
use crabport_terminal::terminal::{BackendEvent, ExecCancel, ExecOutput, SftpTransferKind};
use crate::limits::{
AGENT_READ_LINES, EXEC_CAPTURE_TIMEOUT, OUTPUT_POLL, OUTPUT_QUIET, OUTPUT_TIMEOUT,
SFTP_LIST_TIMEOUT, SFTP_TRANSFER_TIMEOUT, TUNNEL_START_TIMEOUT,
};
use crate::session::AgentSession;
use crate::sftp::format_remote_listing;
use crate::shell::with_cwd;
use crate::text::{cap_tool_result, new_since};
use crate::tools::ToolKind;
use crate::tunnel::{AgentTunnel, AgentTunnelState};
/// What one tool call produced.
#[derive(Clone, Default)]
pub struct ToolOutcome {
/// The text handed back to the model (the approval card renders it too).
pub text: String,
/// The tabular view of the result, when the result is an enumerable
/// list. The model's copy (in `text`) is the same cells as JSON; the card
/// renders the table natively instead of letting the model re-render
/// markdown over it.
pub table: Option<ToolTable>,
/// Exit status of a captured command, when the backend reported one.
pub exit_code: Option<u32>,
/// A captured command outlived its deadline; the output is what was
/// captured before that.
pub timed_out: bool,
/// The user stopped the call while it ran.
pub cancelled: bool,
}
/// A list-style tool result as labelled cells: what the panel renders as a
/// native table, and what the model receives as JSON objects keyed by the
/// headers.
#[derive(Clone, Debug)]
pub struct ToolTable {
pub headers: Vec<String>,
pub rows: Vec<Vec<String>>,
}
impl ToolOutcome {
/// An outcome that is plain text and nothing else.
pub fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),
..Default::default()
}
}
/// A list result: the model's text is the rows as a JSON array of
/// objects (headers as keys), the panel renders the table.
pub fn table(headers: &[&str], rows: Vec<Vec<String>>) -> Self {
let headers: Vec<String> = headers.iter().map(|header| header.to_string()).collect();
let text = table_json(&headers, &rows);
Self {
text,
table: Some(ToolTable { headers, rows }),
..Default::default()
}
}
}
/// Serialize labelled rows as a compact JSON array of objects, one per row.
/// Derived from the same cells the card's table renders, so what the model
/// reasons over and what the user sees cannot drift.
fn table_json(headers: &[String], rows: &[Vec<String>]) -> String {
let objects: Vec<Value> = rows
.iter()
.map(|row| {
let mut object = serde_json::Map::new();
for (header, cell) in headers.iter().zip(row) {
object.insert(header.clone(), Value::String(cell.clone()));
}
Value::Object(object)
})
.collect();
serde_json::to_string(&objects).unwrap_or_default()
}
/// How a tool call is running.
pub enum Executed {
/// The result is ready.
Done(ToolOutcome),
/// Work started. The outcome arrives exactly once on the receiver, and
/// `cancel` stops the call (the card's stop button) — for a visible run
/// that ends the *wait*, not the command in the user's terminal.
Pending {
outcome: Receiver<ToolOutcome>,
cancel: ExecCancel,
},
/// The call could not start: missing or malformed arguments, or a
/// capability this session turned out not to have. The text says why, and
/// the card shows it as a refusal.
Refused(String),
}
/// One conversation's tool runner.
pub struct Agent {
/// Tunnels the agent defined here, in creation order. Shared with the
/// tasks that start them, so a completion can record its state.
tunnels: Arc<Mutex<Vec<AgentTunnel>>>,
next_tunnel_id: u64,
}
impl Agent {
pub fn new() -> Self {
Self {
tunnels: Arc::new(Mutex::new(Vec::new())),
next_tunnel_id: 1,
}
}
/// Whether this tool can run on the session at all; `Some(reason)` blocks
/// it, and the card says so without offering a decision that would do
/// nothing.
pub fn blocked_reason(&self, session: &dyn AgentSession, name: &str) -> Option<String> {
match ToolKind::of(name) {
ToolKind::ExecCapture if !session.allow_exec_capture() => {
Some(t!("ai_panel.tool_exec_unsupported").to_string())
}
ToolKind::Tunnel if !session.allow_tunnels() => {
Some(t!("ai_panel.tool_no_tunnel").to_string())
}
ToolKind::Sftp if !session.allow_sftp() => {
Some(t!("ai_panel.tool_no_sftp").to_string())
}
_ => None,
}
}
/// One-line description of the tunnel a `tunnel_*` call refers to, for its
/// approval card. `None` when the token isn't one of this agent's own.
pub fn describe_tunnel_token(
&self,
manager: Option<&Arc<TunnelManager>>,
token: &str,
) -> Option<String> {
let agent_id = token
.strip_prefix('a')
.and_then(|number| number.parse::<u64>().ok())?;
let tunnels = self.tunnels.lock().unwrap_or_else(|e| e.into_inner());
tunnels
.iter()
.find(|tunnel| tunnel.agent_id == agent_id)
.map(|tunnel| tunnel.describe(manager))
}
/// Run one approved call. `args` is the model's parsed argument object.
pub fn run(&mut self, session: &Arc<dyn AgentSession>, name: &str, args: &Value) -> Executed {
match ToolKind::of(name) {
ToolKind::TerminalRead => self.read_terminal(session, args),
ToolKind::ExecCapture => match command_arg(args) {
Some(command) => self.start_capture(session, &command, ExecCancel::default()),
None => Executed::Refused(t!("ai_panel.tool_bad_args").to_string()),
},
ToolKind::Run => match command_arg(args) {
Some(command) => self.start_visible_run(session, &command, ExecCancel::default()),
None => Executed::Refused(t!("ai_panel.tool_bad_args").to_string()),
},
ToolKind::Fetch => self.start_fetch(args),
ToolKind::LocalFs => self.start_local_fs(name, args),
ToolKind::Sftp => match name {
"sftp_list" => self.start_sftp_list(session, args),
_ => self.start_sftp_transfer(session, name, args),
},
ToolKind::Tunnel => self.run_tunnel(session, name, args),
ToolKind::Unknown => {
Executed::Refused(t!("ai_panel.tool_unknown", name = name).to_string())
}
}
}
// -- terminal tools -----------------------------------------------------
/// `terminal_read`: hand back the most recent screenful.
fn read_terminal(&self, session: &Arc<dyn AgentSession>, args: &Value) -> Executed {
let lines = args
.get("lines")
.and_then(|lines| lines.as_u64())
.unwrap_or(200) as usize;
let text = session.dump_text(lines);
let text = if text.trim().is_empty() {
t!("ai_panel.tool_read_empty").to_string()
} else {
text
};
Executed::Done(ToolOutcome::text(text))
}
/// `terminal_exec`: out of band, output captured directly. The command
/// runs where the user's shell is (when it has reported a directory).
fn start_capture(
&self,
session: &Arc<dyn AgentSession>,
command: &str,
cancel: ExecCancel,
) -> Executed {
if !session.allow_exec_capture() {
return Executed::Refused(t!("ai_panel.tool_exec_unsupported").to_string());
}
let effective = with_cwd(command, session.cwd().as_deref());
let (tx, rx) = bounded(1);
session.exec_capture(
&effective,
EXEC_CAPTURE_TIMEOUT,
cancel.clone(),
Arc::new(move |out: ExecOutput| {
let text = cap_tool_result(out.output.trim_matches('\n'));
let text = if text.trim().is_empty() {
t!("ai_panel.tool_exec_no_output").to_string()
} else {
text
};
let _ = tx.try_send(ToolOutcome {
text,
exit_code: out.exit_code,
timed_out: out.timed_out,
cancelled: out.cancelled,
..Default::default()
});
}),
);
Executed::Pending {
outcome: rx,
cancel,
}
}
/// `terminal_run`: type the line into the live shell and wait for its
/// output to settle. "Settled" is a heuristic — a shell gives no
/// completion signal without OSC 133 — so the screen is sampled every
/// [`OUTPUT_POLL`] and counts as done after [`OUTPUT_QUIET`] without
/// change, or after [`OUTPUT_TIMEOUT`] when it keeps printing.
fn start_visible_run(
&self,
session: &Arc<dyn AgentSession>,
command: &str,
cancel: ExecCancel,
) -> Executed {
let before = session.dump_text(AGENT_READ_LINES);
let mut bytes = command.as_bytes().to_vec();
bytes.push(b'\r');
session.write_raw(&bytes);
let session = session.clone();
let task_cancel = cancel.clone();
let (tx, rx) = bounded(1);
smol::spawn(async move {
let started = Instant::now();
let mut last = before.clone();
let mut quiet_since = Instant::now();
let mut timed_out = false;
let mut cancelled = false;
loop {
smol::Timer::after(OUTPUT_POLL).await;
if task_cancel.is_cancelled() {
cancelled = true;
break;
}
let Some(now) = session.try_dump_text(AGENT_READ_LINES) else {
continue; // terminal lock held by the reader; try next tick
};
if now != last {
last = now;
quiet_since = Instant::now();
} else if quiet_since.elapsed() >= OUTPUT_QUIET {
break;
}
if started.elapsed() >= OUTPUT_TIMEOUT {
timed_out = true;
break;
}
}
let mut text = new_since(&before, &last);
if text.trim().is_empty() {
text = if cancelled {
// The card's caption already says it was stopped; an
// empty body is honest.
String::new()
} else if timed_out {
t!("ai_panel.tool_exec_no_output_timeout").to_string()
} else {
t!("ai_panel.tool_exec_no_output").to_string()
};
}
let _ = tx
.send(ToolOutcome {
text,
exit_code: None,
timed_out,
cancelled,
..Default::default()
})
.await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel,
}
}
// -- local & network tools ---------------------------------------------
/// `fetch`: one HTTP request through CrabPort's own client.
fn start_fetch(&self, args: &Value) -> Executed {
let Some(url) = args.get("url").and_then(|url| url.as_str()) else {
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
};
let url = url.to_string();
let proxy = args
.get("proxy")
.and_then(|proxy| proxy.as_str())
.map(str::to_string);
let method = args
.get("method")
.and_then(|method| method.as_str())
.unwrap_or("GET")
.to_ascii_uppercase();
let body = args
.get("body")
.and_then(|body| body.as_str())
.map(str::to_string);
let (tx, rx) = bounded(1);
smol::spawn(async move {
let text = smol::unblock(move || {
crate::fetch::fetch_url(&url, proxy.as_deref(), &method, body.as_deref())
})
.await;
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
/// `read_file` / `read_directory`: the machine CrabPort runs on.
fn start_local_fs(&self, name: &str, args: &Value) -> Executed {
let Some(path) = args.get("path").and_then(|path| path.as_str()) else {
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
};
let path = path.to_string();
let is_file = name == "read_file";
let (tx, rx) = bounded(1);
smol::spawn(async move {
let outcome = smol::unblock(move || {
if is_file {
crate::local_fs::read_local_file(&path)
} else {
crate::local_fs::read_local_directory(&path)
}
})
.await;
let _ = tx.send(outcome).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
// -- sftp tools ---------------------------------------------------------
/// `sftp_list`: navigate the backend and wait for the *fresh* listing.
/// Freshness is the entries `Arc` being replaced — the backend installs a
/// new one on every successful read_dir — because the cwd alone stays put
/// when the requested directory is the one already shown.
fn start_sftp_list(&self, session: &Arc<dyn AgentSession>, args: &Value) -> Executed {
if !session.allow_sftp() {
return Executed::Refused(t!("ai_panel.tool_no_sftp").to_string());
}
let Some(path) = args.get("path").and_then(|path| path.as_str()) else {
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
};
let before = session.sftp_listing().map(|(_, entries)| entries);
session.sftp_navigate(path);
let session = session.clone();
let (tx, rx) = bounded(1);
smol::spawn(async move {
let started = Instant::now();
let mut outcome = None;
while started.elapsed() < SFTP_LIST_TIMEOUT {
smol::Timer::after(OUTPUT_POLL).await;
// The backend logs a failed navigation silently; the timeout
// below is what reports it.
let Some((_cwd, entries)) = session.sftp_listing() else {
continue;
};
let fresh = match &before {
None => true,
Some(old) => !Arc::ptr_eq(old, &entries),
};
if fresh {
outcome = Some(format_remote_listing(&entries));
break;
}
}
let outcome =
outcome.unwrap_or_else(|| ToolOutcome::text(t!("ai_panel.tool_sftp_list_timeout")));
let _ = tx.send(outcome).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
/// `sftp_download` / `sftp_upload`: start the transfer and wait for its
/// completion event — the `SftpTransferFinished` the UI also shows as a
/// toast. The subscription is taken *before* the transfer starts: that
/// event is the only signal a transfer finished.
fn start_sftp_transfer(
&self,
session: &Arc<dyn AgentSession>,
name: &str,
args: &Value,
) -> Executed {
if !session.allow_sftp() {
return Executed::Refused(t!("ai_panel.tool_no_sftp").to_string());
}
let remote = args
.get("remote_path")
.and_then(|path| path.as_str())
.map(str::to_string);
let local = args
.get("local_path")
.and_then(|path| path.as_str())
.map(str::to_string);
let (Some(remote), Some(local)) = (remote, local) else {
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
};
let kind = if name == "sftp_download" {
SftpTransferKind::Download
} else {
SftpTransferKind::Upload
};
let Some(mut events) = session.subscribe_events() else {
return Executed::Refused(t!("ai_panel.tool_no_sftp").to_string());
};
if name == "sftp_download" {
session.sftp_download(&remote, &local);
} else {
session.sftp_upload(&local, &remote);
}
let (tx, rx) = bounded(1);
smol::spawn(async move {
let started = Instant::now();
let mut outcome: Option<(bool, String)> = None;
while outcome.is_none() && started.elapsed() < SFTP_TRANSFER_TIMEOUT {
smol::Timer::after(OUTPUT_POLL).await;
loop {
match events.try_recv() {
Ok(BackendEvent::SftpTransferFinished {
kind: finished,
success,
message,
}) => {
if finished == kind {
outcome = Some((success, message));
break;
}
}
Ok(_) => continue,
Err(_) => break,
}
}
}
let text = match outcome {
Some((true, message)) => {
t!("ai_panel.tool_sftp_done", message = message).to_string()
}
Some((false, message)) => {
t!("ai_panel.tool_sftp_failed", message = message).to_string()
}
None => t!(
"ai_panel.tool_sftp_transfer_timeout",
mins = (SFTP_TRANSFER_TIMEOUT.as_secs() / 60).to_string()
)
.to_string(),
};
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
// -- tunnel tools -------------------------------------------------------
/// `tunnel_list` / `tunnel_create` / `tunnel_open` / `tunnel_close` /
/// `tunnel_delete`. Id tokens decide where a tunnel lives: `a<N>` is one
/// this agent created, `t<N>` a Tunnels-page config bound to this
/// session's host.
fn run_tunnel(
&mut self,
session: &Arc<dyn AgentSession>,
name: &str,
args: &Value,
) -> Executed {
match name {
"tunnel_list" => Executed::Done(self.tunnel_list_outcome(session)),
"tunnel_create" => self.tunnel_create(args),
"tunnel_open" | "tunnel_close" | "tunnel_delete" => {
let Some(token) = args.get("tunnel_id").and_then(|id| id.as_str()) else {
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
};
let (prefix, number) = split_token(token);
match (prefix, number) {
('a', Some(agent_id)) => match name {
"tunnel_open" => self.tunnel_open(session, agent_id),
"tunnel_close" => self.tunnel_close(session, agent_id),
_ => self.tunnel_delete(session, agent_id),
},
('t', Some(config_id)) => self.registry_op(session, name, config_id as i64),
_ => Executed::Refused(
t!("ai_panel.tool_tunnel_unknown", id = token).to_string(),
),
}
}
other => Executed::Refused(t!("ai_panel.tool_unknown", name = other).to_string()),
}
}
/// The tunnel list: the agent's own first (their ids are the actionable
/// ones), then the Tunnels-page configs for this host. The model receives
/// the rows as JSON (a `tool` message), the card renders the same cells
/// as a table — see [`ToolOutcome::table`].
fn tunnel_list_outcome(&self, session: &Arc<dyn AgentSession>) -> ToolOutcome {
let manager = session.tunnel_manager();
let mut rows: Vec<Vec<String>> = Vec::new();
{
let tunnels = self.tunnels.lock().unwrap_or_else(|e| e.into_inner());
rows.extend(
tunnels
.iter()
.map(|tunnel| tunnel.list_row(manager.as_ref())),
);
}
for view in session.registry_tunnels() {
let source = if view.borrowed {
t!("ai_panel.tunnel_source_borrowed")
} else {
t!("ai_panel.tunnel_source_owned")
};
// Both ends of a local/remote tunnel go into one cell — the model
// needs host *and* port to use or talk about it.
let mut address = format!("{}:{}", view.bind_addr, view.bind_port);
if !view.target_host.is_empty() && view.target_port != 0 {
address.push_str(&format!(" -> {}:{}", view.target_host, view.target_port));
}
let status = if view.running {
t!("ai_panel.tunnel_state_running")
} else {
t!("ai_panel.tunnel_state_stopped")
};
rows.push(vec![
format!("t{}", view.id),
view.name,
view.kind.as_str().to_string(),
address,
format!("{status} · {source}"),
]);
}
if rows.is_empty() {
return ToolOutcome::text(t!("ai_panel.tool_tunnel_list_empty"));
}
ToolOutcome::table(&["id", "name", "kind", "address", "status"], rows)
}
/// Define a session-local tunnel. Not started, never persisted.
fn tunnel_create(&mut self, args: &Value) -> Executed {
let kind = TunnelKind::from_str(
args.get("kind")
.and_then(|kind| kind.as_str())
.unwrap_or("dynamic"),
);
let name = args
.get("name")
.and_then(|name| name.as_str())
.map(str::to_string)
.unwrap_or_else(|| format!("agent-tunnel-{}", self.next_tunnel_id));
let bind_port = args
.get("bind_port")
.and_then(|port| port.as_u64())
.unwrap_or(0) as u16;
let bind_addr = args
.get("bind_addr")
.and_then(|addr| addr.as_str())
.unwrap_or("127.0.0.1")
.to_string();
let target_host = args
.get("target_host")
.and_then(|host| host.as_str())
.unwrap_or("")
.to_string();
let target_port = args
.get("target_port")
.and_then(|port| port.as_u64())
.unwrap_or(0) as u16;
// local/remote need a target: refuse the malformed definition instead
// of keeping something that can never start.
if matches!(kind, TunnelKind::Local | TunnelKind::Remote)
&& (target_host.is_empty() || target_port == 0)
{
return Executed::Refused(t!("ai_panel.tool_bad_args").to_string());
}
let agent_id = self.next_tunnel_id;
self.next_tunnel_id += 1;
let tunnel = AgentTunnel {
agent_id,
kind,
name,
bind_addr,
bind_port,
target_host,
target_port,
state: AgentTunnelState::Created,
};
let handle = tunnel.handle();
self.tunnels
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(tunnel);
Executed::Done(ToolOutcome::text(
t!("ai_panel.tool_tunnel_created", id = handle).to_string(),
))
}
/// Start one of the agent's own tunnels and wait until it is actually
/// listening (or failed), so the model can use the port right away.
fn tunnel_open(&self, session: &Arc<dyn AgentSession>, agent_id: u64) -> Executed {
let spec = {
let tunnels = self.tunnels.lock().unwrap_or_else(|e| e.into_inner());
tunnels
.iter()
.find(|tunnel| tunnel.agent_id == agent_id)
.cloned()
};
let Some(spec) = spec else {
return Executed::Refused(
t!("ai_panel.tool_tunnel_unknown", id = format!("a{agent_id}")).to_string(),
);
};
if matches!(spec.state, AgentTunnelState::Running(_)) {
return Executed::Done(ToolOutcome::text(
t!("ai_panel.tool_tunnel_already").to_string(),
));
}
let Some(manager) = session.tunnel_manager() else {
return Executed::Refused(t!("ai_panel.tool_no_tunnel").to_string());
};
let tunnels = self.tunnels.clone();
let (tx, rx) = bounded(1);
smol::spawn(async move {
let manager_for_start = manager.clone();
let kind = spec.kind;
let name = spec.name.clone();
let bind_addr = spec.bind_addr.clone();
let (bind_port, target_host, target_port) =
(spec.bind_port, spec.target_host.clone(), spec.target_port);
let outcome = smol::unblock(move || {
let start = async {
match kind {
TunnelKind::Dynamic => {
manager_for_start
.start_dynamic(name, bind_addr, bind_port)
.await
}
TunnelKind::Local => {
manager_for_start
.start_local(name, bind_addr, bind_port, target_host, target_port)
.await
}
TunnelKind::Remote => {
manager_for_start
.start_remote(name, bind_addr, bind_port, target_host, target_port)
.await
}
}
};
TOKIO.block_on(start)
})
.await;
let result = match outcome {
Ok(tunnel_id) => {
let started_at = Instant::now();
loop {
match manager.get(tunnel_id).map(|info| info.status) {
Some(TunnelStatus::Active) => break Ok(tunnel_id),
Some(TunnelStatus::Failed(reason)) => break Err(reason),
Some(TunnelStatus::Closed) => {
break Err("tunnel closed while starting".to_string());
}
_ if started_at.elapsed() >= TUNNEL_START_TIMEOUT => {
break Err(format!(
"still starting after {}s",
TUNNEL_START_TIMEOUT.as_secs()
));
}
_ => {
smol::Timer::after(std::time::Duration::from_millis(100)).await;
}
}
}
}
Err(reason) => Err(reason),
};
let text = {
let mut guard = tunnels.lock().unwrap_or_else(|e| e.into_inner());
match guard.iter_mut().find(|tunnel| tunnel.agent_id == agent_id) {
Some(spec) => {
match &result {
Ok(tunnel_id) => spec.state = AgentTunnelState::Running(*tunnel_id),
Err(reason) => spec.state = AgentTunnelState::Failed(reason.clone()),
}
match &result {
Ok(_) => spec.describe(Some(&manager)),
Err(reason) => {
format!("{}: {reason}", t!("ai_panel.tool_tunnel_open_failed"))
}
}
}
None => String::new(),
}
};
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
/// Stop one of the agent's own tunnels. The manager's entry goes away;
/// the definition stays and can be opened again.
fn tunnel_close(&self, session: &Arc<dyn AgentSession>, agent_id: u64) -> Executed {
let running = {
let tunnels = self.tunnels.lock().unwrap_or_else(|e| e.into_inner());
match tunnels
.iter()
.find(|tunnel| tunnel.agent_id == agent_id)
.map(|tunnel| &tunnel.state)
{
Some(AgentTunnelState::Running(tunnel_id)) => Some(*tunnel_id),
Some(_) => None,
None => {
return Executed::Refused(
t!("ai_panel.tool_tunnel_unknown", id = format!("a{agent_id}")).to_string(),
);
}
}
};
let Some(tunnel_id) = running else {
return Executed::Done(ToolOutcome::text(
t!(
"ai_panel.tool_tunnel_not_running",
id = format!("a{agent_id}")
)
.to_string(),
));
};
let Some(manager) = session.tunnel_manager() else {
return Executed::Refused(t!("ai_panel.tool_no_tunnel").to_string());
};
let tunnels = self.tunnels.clone();
let (tx, rx) = bounded(1);
smol::spawn(async move {
smol::unblock(move || TOKIO.block_on(manager.stop(tunnel_id))).await;
{
let mut guard = tunnels.lock().unwrap_or_else(|e| e.into_inner());
if let Some(spec) = guard.iter_mut().find(|tunnel| tunnel.agent_id == agent_id) {
spec.state = AgentTunnelState::Closed;
}
}
let text = t!("ai_panel.tool_tunnel_closed", id = format!("a{agent_id}")).to_string();
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
/// Delete one of the agent's own tunnels, stopping it first when it runs.
/// The slot stays (marked deleted) so earlier tokens remain unambiguous.
fn tunnel_delete(&self, session: &Arc<dyn AgentSession>, agent_id: u64) -> Executed {
let running = {
let tunnels = self.tunnels.lock().unwrap_or_else(|e| e.into_inner());
match tunnels
.iter()
.find(|tunnel| tunnel.agent_id == agent_id)
.map(|tunnel| &tunnel.state)
{
Some(AgentTunnelState::Running(tunnel_id)) => Some(*tunnel_id),
Some(_) => None,
None => {
return Executed::Refused(
t!("ai_panel.tool_tunnel_unknown", id = format!("a{agent_id}")).to_string(),
);
}
}
};
let manager = running.and_then(|_| session.tunnel_manager());
let tunnels = self.tunnels.clone();
let (tx, rx) = bounded(1);
smol::spawn(async move {
if let (Some(tunnel_id), Some(manager)) = (running, manager) {
smol::unblock(move || TOKIO.block_on(manager.stop(tunnel_id))).await;
}
{
let mut guard = tunnels.lock().unwrap_or_else(|e| e.into_inner());
if let Some(spec) = guard.iter_mut().find(|tunnel| tunnel.agent_id == agent_id) {
spec.state = AgentTunnelState::Deleted;
}
}
let text = t!("ai_panel.tool_tunnel_deleted", id = format!("a{agent_id}")).to_string();
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
/// Open / close / delete a *Tunnels-page* config bound to this session's
/// host. The UI routes the mutations through the app's own tunnel
/// machinery; this only waits for the registry to reflect them.
fn registry_op(&self, session: &Arc<dyn AgentSession>, name: &str, config_id: i64) -> Executed {
let token = format!("t{config_id}");
let known = session
.registry_tunnels()
.iter()
.any(|view| view.id == config_id);
if !known {
return Executed::Refused(t!("ai_panel.tool_tunnel_unknown", id = token).to_string());
}
let session = session.clone();
let (tx, rx) = bounded(1);
match name {
"tunnel_open" => {
if session.registry_is_running(config_id) {
return Executed::Done(ToolOutcome::text(
t!("ai_panel.tool_tunnel_already").to_string(),
));
}
session.registry_open(config_id);
smol::spawn(async move {
let started_at = Instant::now();
let mut running = false;
while started_at.elapsed() < TUNNEL_START_TIMEOUT {
if session.registry_is_running(config_id) {
running = true;
break;
}
smol::Timer::after(std::time::Duration::from_millis(120)).await;
}
let text = match (running, session.registry_live(config_id)) {
(true, Some((bind_addr, bind_port, target_host, target_port))) => {
let mut text = format!(
"{token} — {}",
t!(
"ai_panel.tunnel_running_at",
bind = format!("{bind_addr}:{bind_port}")
)
);
if !target_host.is_empty() && target_port != 0 {
text.push_str(&format!(" -> {target_host}:{target_port}"));
}
text
}
(true, None) => token.clone(),
(false, _) => format!(
"{}: {}",
t!("ai_panel.tool_tunnel_open_failed"),
t!("ai_panel.tunnel_start_timeout")
),
};
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
}
"tunnel_close" => {
if !session.registry_is_running(config_id) {
return Executed::Done(ToolOutcome::text(
t!("ai_panel.tool_tunnel_not_running", id = token).to_string(),
));
}
session.registry_close(config_id);
smol::spawn(async move {
let started_at = Instant::now();
while session.registry_is_running(config_id)
&& started_at.elapsed() < TUNNEL_START_TIMEOUT
{
smol::Timer::after(std::time::Duration::from_millis(120)).await;
}
let text = t!("ai_panel.tool_tunnel_closed", id = token).to_string();
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
}
_ => {
session.registry_delete(config_id);
smol::spawn(async move {
let started_at = Instant::now();
while session
.registry_tunnels()
.iter()
.any(|view| view.id == config_id)
&& started_at.elapsed() < TUNNEL_START_TIMEOUT
{
smol::Timer::after(std::time::Duration::from_millis(120)).await;
}
let text = t!("ai_panel.tool_tunnel_deleted", id = token).to_string();
let _ = tx.send(ToolOutcome::text(text)).await;
})
.detach();
}
}
Executed::Pending {
outcome: rx,
cancel: ExecCancel::default(),
}
}
}
/// The `command` argument both execution tools take.
fn command_arg(args: &Value) -> Option<String> {
args.get("command")
.and_then(|command| command.as_str())
.map(str::to_string)
}
/// `"a12"` → `('a', Some(12))`; malformed tokens yield no number.
fn split_token(token: &str) -> (char, Option<u64>) {
(
token.chars().next().unwrap_or(' '),
token[1..].parse::<u64>().ok(),
)
}
#[cfg(test)]
mod tests {
use super::*;
/// A list result reaches the model as a JSON array of objects keyed by
/// the headers — the same cells the card renders as a table.
#[test]
fn table_outcome_serializes_rows_as_objects() {
let outcome =
ToolOutcome::table(&["id", "status"], vec![vec!["a1".into(), "running".into()]]);
assert_eq!(outcome.text, r#"[{"id":"a1","status":"running"}]"#);
let table = outcome.table.expect("table present");
assert_eq!(table.headers, ["id", "status"]);
assert_eq!(
table.rows,
vec![vec!["a1".to_string(), "running".to_string()]]
);
}
}
# ===== file: crabport-agent/src/compaction.rs =====
//! Automatic context compaction: how big a conversation has grown, where to
//! cut it, and the transcript handed to the summarizer.
//!
//! UI-free by construction: callers map their own message representation into
//! [`CompactTurn`] slices, so one set of rules applies no matter what renders
//! the conversation.
use crabport_ai::{MESSAGE_OVERHEAD_TOKENS, TOOL_CALL_OVERHEAD_TOKENS, estimate_tokens};
/// Longest single tool result fed into a compaction transcript, in bytes. The
/// transcript is the *summarizer's input*, so a handful of huge command
/// outputs must not blow up the very request meant to shrink the
/// conversation; [`cap_for_summary`] keeps the tail of a longer result, where
/// a command's errors and summary usually are.
pub const COMPACT_RESULT_CAP: usize = 4 * 1024;
/// Instruction for a compaction round: what the summary must preserve so the
/// work can continue without the original messages.
pub const COMPACTION_PROMPT: &str = "\
You maintain the working memory of a terminal-operating agent. Summarize the \
conversation transcript below into notes for yourself, so the work can \
continue without the original messages. Preserve: the user's goals and \
constraints (and anything they asked you to remember), decisions made, the \
commands that ran with their key output (paths, errors, numbers), the state \
of anything still running, and open questions. Be specific and terse — no \
pleasantries, no restating the obvious. Reply with the summary only, as \
Markdown.";
/// Preamble for a compaction summary in the wire history. Spelled out so the
/// model reads it as context rather than as a fresh instruction.
pub const COMPACTED_HEADER: &str =
"Summary of the earlier conversation, compacted to save context:\n\n";
/// Author of one turn in the compaction view.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TurnRole {
User,
Assistant,
/// A summary standing in for everything older (already compacted once).
Summary,
}
/// One tool call inside an assistant turn, as the compaction helpers see it.
pub struct CompactCall<'a> {
pub name: &'a str,
pub arguments: &'a str,
/// The result the call produced, when it ran.
pub result: Option<&'a str>,
}
/// One conversation turn, borrowed from the caller's own message type.
pub struct CompactTurn<'a> {
pub role: TurnRole,
pub content: &'a str,
pub tool_calls: Vec<CompactCall<'a>>,
}
/// Rough token size of one turn, matching what its wire form costs: the
/// content plus every tool call's arguments and result. Reasoning is not
/// counted — it is display-only and never replayed.
pub fn message_tokens(turn: &CompactTurn<'_>) -> usize {
let mut total = MESSAGE_OVERHEAD_TOKENS + estimate_tokens(turn.content);
for call in &turn.tool_calls {
total += TOOL_CALL_OVERHEAD_TOKENS
+ estimate_tokens(call.name)
+ estimate_tokens(call.arguments)
+ call.result.map(estimate_tokens).unwrap_or(0);
}
total
}
/// Index of the first turn to keep verbatim when compacting a conversation.
///
/// Walks backwards, keeping turns until roughly `keep_tokens` is reached, then
/// snaps the cut back to the user turn that opened that block: an assistant's
/// tool calls and their results must travel together, and the kept tail reads
/// best starting with the user's ask. `0` means "nothing old enough to
/// summarize" — the caller then leaves the history alone.
pub fn compaction_cut(turns: &[CompactTurn<'_>], keep_tokens: usize) -> usize {
let mut used = 0usize;
for (ix, turn) in turns.iter().enumerate().rev() {
used += message_tokens(turn);
if used >= keep_tokens {
return turns[..=ix]
.iter()
.rposition(|turn| turn.role == TurnRole::User)
.unwrap_or(0);
}
}
0
}
/// Plain-text transcript of the turns being compacted, for the summarizer.
///
/// Tool results are capped ([`COMPACT_RESULT_CAP`], tail kept) so a few huge
/// command outputs can't make the compaction request larger than the
/// conversation it is meant to shrink.
pub fn compaction_transcript(turns: &[CompactTurn<'_>]) -> String {
let mut out = String::new();
for turn in turns {
match turn.role {
TurnRole::User => {
out.push_str("USER: ");
out.push_str(turn.content.trim());
out.push('\n');
}
TurnRole::Summary => {
out.push_str("SUMMARY SO FAR: ");
out.push_str(turn.content.trim());
out.push('\n');
}
TurnRole::Assistant => {
if !turn.content.trim().is_empty() {
out.push_str("ASSISTANT: ");
out.push_str(turn.content.trim());
out.push('\n');
}
for call in &turn.tool_calls {
out.push_str(" [");
out.push_str(call.name);
out.push_str("] ");
out.push_str(call.arguments.trim());
if let Some(result) = call.result {
out.push_str(" -> ");
out.push_str(cap_for_summary(result.trim()));
}
out.push('\n');
}
}
}
}
out
}
/// `text` shortened to [`COMPACT_RESULT_CAP`] from the front (keeping the
/// tail, where a command's errors and summary usually are) when it is longer.
pub fn cap_for_summary(text: &str) -> &str {
if text.len() <= COMPACT_RESULT_CAP {
return text;
}
let mut cut = text.len() - COMPACT_RESULT_CAP;
while cut < text.len() && !text.is_char_boundary(cut) {
cut += 1;
}
&text[cut..]
}
#[cfg(test)]
mod tests {
use super::{
COMPACT_RESULT_CAP, CompactCall, CompactTurn, TurnRole, compaction_cut,
compaction_transcript, message_tokens,
};
fn msg(role: TurnRole, content: &'static str) -> CompactTurn<'static> {
CompactTurn {
role,
content,
tool_calls: Vec::new(),
}
}
/// Compaction keeps the recent tail and snaps its cut back to a user
/// turn, so an assistant's tool calls never get separated from the
/// results that answer them.
#[test]
fn compaction_cut_keeps_recent_turns_and_snaps_to_user() {
let turns = vec![
msg(TurnRole::User, "u1"),
msg(TurnRole::Assistant, "a1"),
msg(TurnRole::User, "u2"),
msg(TurnRole::Assistant, "a2"),
msg(TurnRole::User, "u3"),
];
// A tiny budget keeps only the newest user turn.
assert_eq!(compaction_cut(&turns, 1), 4);
// A budget covering `u3` and `a2` snaps back to the turn that opened
// the block: `a2` must not travel without `u2`.
let keep = message_tokens(&turns[4]) + message_tokens(&turns[3]);
assert_eq!(compaction_cut(&turns, keep), 2);
// Everything fits: nothing old enough to summarize.
assert_eq!(compaction_cut(&turns, usize::MAX), 0);
assert_eq!(compaction_cut(&[], 10), 0);
}
/// The transcript fed to the summarizer labels roles, carries tool calls
/// with their results, and caps huge results so the compaction request
/// cannot be bigger than the history it is shrinking.
#[test]
fn compaction_transcript_labels_roles_and_caps_results() {
let long_result = "x".repeat(COMPACT_RESULT_CAP * 2);
let assistant = CompactTurn {
role: TurnRole::Assistant,
content: "done",
tool_calls: vec![CompactCall {
name: "terminal_exec",
arguments: r#"{"command":"ls"}"#,
result: Some(&long_result),
}],
};
let text = compaction_transcript(&[msg(TurnRole::User, "hi"), assistant]);
assert!(text.contains("USER: hi"), "{text}");
assert!(
text.contains("[terminal_exec] {\"command\":\"ls\"} -> "),
"{text}"
);
// The capped result must not carry more than one cap of text.
assert!(!text.contains(&"x".repeat(COMPACT_RESULT_CAP + 1)));
}
}
# ===== file: crabport-agent/src/fetch.rs =====
//! `fetch` — one HTTP request through CrabPort's own client, optionally via
//! a proxy URL (a dynamic tunnel's socks5h endpoint is the usual case).
use crate::limits::FETCH_TIMEOUT;
use crate::text::cap_tool_result_head;
/// Most bytes of an HTTP body a `fetch` reads before capping. Bounds the
/// memory the read holds; the result is capped again for the model.
const FETCH_BODY_LIMIT: u64 = 256 * 1024;
/// Send one HTTP request with CrabPort's own HTTP client, optionally through
/// a proxy URL, and return the text to hand back to the model. Never fails:
/// every problem becomes readable text.
pub fn fetch_url(url: &str, proxy: Option<&str>, method: &str, body: Option<&str>) -> String {
let mut config = ureq::Agent::config_builder().timeout_global(Some(FETCH_TIMEOUT));
if let Some(proxy_url) = proxy {
match ureq::Proxy::new(proxy_url) {
Ok(proxy) => config = config.proxy(Some(proxy)),
Err(err) => return format!("invalid proxy url: {err}"),
}
}
let agent = ureq::Agent::new_with_config(config.build());
let outcome = match method {
"POST" => agent.post(url).send(body.unwrap_or_default()),
"PUT" => agent.put(url).send(body.unwrap_or_default()),
"DELETE" => agent.delete(url).call(),
"HEAD" => agent.head(url).call(),
_ => agent.get(url).call(),
};
match outcome {
Ok(mut resp) => {
let mut text = format!("HTTP {}\n", resp.status());
for (name, value) in resp.headers() {
text.push_str(&format!("{name}: {}\n", value.to_str().unwrap_or("…")));
}
match resp
.body_mut()
.with_config()
.limit(FETCH_BODY_LIMIT)
.read_to_string()
{
Ok(body_text) => {
text.push('\n');
text.push_str(&cap_tool_result_head(body_text.trim_end()));
}
Err(err) => text.push_str(&format!("\n(body unreadable: {err})")),
}
text
}
Err(err) => format!("request failed: {err}"),
}
}
# ===== file: crabport-agent/src/lib.rs =====
//! The CrabPort agent: everything the built-in assistant does *beyond*
//! talking — the prompt it runs under, the tools it may call, and the
//! implementations behind those tools (captured and visible command
//! execution, local file reads, HTTP fetches, tunnel lifecycle, SFTP).
//!
//! Free of GPUI by construction: the UI implements [`session::AgentSession`]
//! over its terminal view and shared handles, and [`agent::Agent`] runs the
//! tools — including their polling loops — on background threads. The UI only
//! awaits the result and renders it.
//!
//! Translations: `t!` resolves a crate-local backend, so this crate loads the
//! app's locale files itself (the keys are shared with `crabport-ui/i18n`;
//! `set_locale` is process-global, so language switches stay in sync).
rust_i18n::i18n!("../crabport-ui/i18n", fallback = "en");
pub mod agent;
pub mod compaction;
pub mod fetch;
pub mod limits;
pub mod local_fs;
pub mod prompt;
pub mod session;
pub mod sftp;
pub mod shell;
pub mod text;
pub mod tools;
pub mod tunnel;
pub use agent::{Agent, Executed, ToolOutcome, ToolTable};
pub use compaction::{
COMPACTED_HEADER, COMPACTION_PROMPT, CompactCall, CompactTurn, TurnRole, compaction_cut,
compaction_transcript,
};
pub use prompt::system_prompt;
pub use session::{AgentSession, RegistryTunnel};
pub use tools::{TOOL_NAMES, ToolKind, agent_tools};
# ===== file: crabport-agent/src/limits.rs =====
//! Timeouts and result caps for the agent's tools, in one place.
/// How many lines of terminal output a `terminal_read` (and the execute
/// output wait) samples. Plenty for a screenful plus recent scrollback.
pub const AGENT_READ_LINES: usize = 400;
/// How often the execute wait re-samples the terminal's output.
pub const OUTPUT_POLL: std::time::Duration = std::time::Duration::from_millis(120);
/// How long the output must stop changing before a command counts as done.
pub const OUTPUT_QUIET: std::time::Duration = std::time::Duration::from_millis(360);
/// Upper bound on the wait: a command that keeps printing (a log tail, a
/// build) gets this long before its output-so-far is handed over.
pub const OUTPUT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(12);
/// Cap on the text one tool result may carry back to the model, in bytes. A
/// command that prints a whole file would otherwise fill the conversation's
/// context with one answer; the *tail* is kept, which is where a command's
/// interesting output (errors, the final summary) usually is.
pub const MAX_TOOL_RESULT_BYTES: usize = 16 * 1024;
/// How long a captured (`terminal_exec`) command may run before its backend
/// gives up and hands over the output so far. Generous enough for a normal
/// non-interactive command, bounded so a `tail -f`-style slip-up cannot
/// wedge the conversation forever.
pub const EXEC_CAPTURE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
/// Most bytes a `read_file` loads before the result is capped for the model.
/// Big enough for any source file or config, small enough that pointing the
/// tool at a video cannot stall the panel.
pub const READ_FILE_LIMIT: u64 = 256 * 1024;
/// Most entries a `read_directory` lists before it says there were more.
pub const READ_DIR_LIMIT: usize = 500;
/// `fetch`'s overall HTTP timeout — a hung request must not wedge the
/// conversation any more than a hung command may.
pub const FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
/// How long `sftp_list` waits for the backend's navigation to land before it
/// reports the directory as unreadable (the backend logs failures silently).
/// The first listing on a session also pays the SFTP subsystem handshake, so
/// this is generous.
pub const SFTP_LIST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// How long an SFTP transfer may run before the tool call reports what has
/// happened so far. Long — transfers can genuinely take minutes — but bounded.
pub const SFTP_TRANSFER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
/// How long a tunnel's start may stay in "starting" before `tunnel_open`
/// reports it failed.
pub const TUNNEL_START_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
# ===== file: crabport-agent/src/local_fs.rs =====
//! `read_file` / `read_directory` — the machine CrabPort itself runs on.
use std::io::Read as _;
use rust_i18n::t;
use crate::agent::ToolOutcome;
use crate::limits::{READ_DIR_LIMIT, READ_FILE_LIMIT};
use crate::text::cap_tool_result_head;
/// Read up to [`READ_FILE_LIMIT`] bytes of a local file; binary content is
/// reported rather than dumped. Never fails — every problem becomes text.
pub fn read_local_file(path: &str) -> ToolOutcome {
let file = match std::fs::File::open(path) {
Ok(file) => file,
Err(err) => return ToolOutcome::text(format!("cannot open {path}: {err}")),
};
let size = file.metadata().map(|meta| meta.len()).unwrap_or(0);
let mut reader = file.take(READ_FILE_LIMIT);
let mut buf = Vec::new();
if reader.read_to_end(&mut buf).is_err() {
return ToolOutcome::text(format!("reading {path} failed: I/O error"));
}
if buf.contains(&0) {
return ToolOutcome::text(t!(
"ai_panel.tool_read_file_binary",
bytes = size.to_string()
));
}
ToolOutcome::text(cap_tool_result_head(&String::from_utf8_lossy(&buf)))
}
/// List a local directory: one table row per entry (name / type / size,
/// as the model sees them — directories say `dir`), capped at
/// [`READ_DIR_LIMIT`]. Never fails — every problem becomes text.
pub fn read_local_directory(path: &str) -> ToolOutcome {
let dir = match std::fs::read_dir(path) {
Ok(dir) => dir,
Err(err) => return ToolOutcome::text(format!("cannot list {path}: {err}")),
};
let mut rows: Vec<Vec<String>> = Vec::new();
let mut overflow = 0usize;
for entry in dir {
let Ok(entry) = entry else { continue };
if rows.len() >= READ_DIR_LIMIT {
overflow += 1;
continue;
}
let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
let name = entry.file_name().to_string_lossy().into_owned();
let kind = if is_dir { "dir" } else { "file" }.to_string();
let size = entry
.metadata()
.map(|meta| meta.len().to_string())
.unwrap_or_else(|_| "?".to_string());
rows.push(vec![name, kind, size]);
}
if rows.is_empty() {
return ToolOutcome::text(t!("ai_panel.tool_dir_empty"));
}
let mut outcome = ToolOutcome::table(&["name", "type", "size"], rows);
if overflow > 0 {
outcome.text.push_str(&format!(
"\n{}",
t!("ai_panel.tool_dir_truncated", more = overflow)
));
}
outcome
}
# ===== file: crabport-agent/src/prompt.rs =====
//! The pinned agent prompts: the base rules every conversation carries, plus
//! a platform note so the model writes local paths the way the host OS
//! expects.
/// Pinned ahead of every conversation.
///
/// The agent prompt: the model may inspect and drive *its own* terminal and
/// this machine, but nothing happens without the user approving it. Keep the
/// rules short and concrete — the tools themselves carry the detail.
const BASE_PROMPT: &str = "\
You are the built-in AI assistant of CrabPort, an SSH/SFTP client, working \
inside one terminal session. Be concise and practical.\n\n\
Every tool call is shown to the user for approval, so call a tool only when \
it earns its place: say why you are reading, and what you expect a call to \
do. Never batch speculative calls — one call, then read the result. When \
the user asks for something you can answer without a tool, just answer.\n\n\
Terminal tools — this session's shell only:\n\
- terminal_read: read the most recent output lines. Use it before asking \
questions the screen can answer, and after a visible command to see what \
happened.\n\
- terminal_exec (your default executor): run one command out of band and get \
its captured stdout, stderr and exit code directly. It does not appear in \
the user's terminal and cannot answer prompts.\n\
- terminal_run: type one command into the user's live terminal, exactly as \
if they typed it, so its output streams where they can watch it. Use it only \
when the output must be followed while it runs or the command is interactive \
(REPLs, anything that may prompt for input such as sudo).\n\n\
Local tools — the machine CrabPort itself runs on, never the remote host:\n\
- read_file: read one local file.\n\
- read_directory: list one local directory.\n\n\
Network:\n\
- fetch: send one HTTP request from inside CrabPort, returning status, \
headers and body. It runs on the local machine's network, not the remote \
host's; pass a proxy URL to route it elsewhere — typically a dynamic tunnel \
you created and opened on this session, as socks5h://127.0.0.1:<port> (the \
h matters: the hostname is then resolved on the remote side).\n\n\
Tunnel tools — the current tab's SSH connection only (tunnels ride it; no \
extra connection is opened; unavailable on local, telnet and serial \
terminals):\n\
- tunnel_list: see the tunnels available here - ids for tunnels you \
created here start with a-N, Tunnels-page configs on this host start \
with t-N; both work with open / close / delete.\n\
- tunnel_create: define a temporary, session-local tunnel (local / dynamic \
/ remote, not started; never persisted); \
tunnel_open starts it and reports the address it listens on, tunnel_close \
stops it, tunnel_delete removes it.\n\
SFTP tools — this session's connection only (unavailable without SFTP):\n\
- sftp_list: list a remote directory — the default way to look at the \
remote filesystem (this also moves the SFTP panel's view there). When this \
session has no SFTP, look at files with shell commands instead \
(terminal_exec: ls, find, du, …).\n\
- sftp_download / sftp_upload: transfer one file between the remote host \
and the local machine.\n\n\
Safety: when a call could have destructive or otherwise high-risk effects — \
deleting or overwriting data, changing system or service configuration, \
touching production, anything hard to undo — repeat it in your reply \
**in bold** and say plainly what could go wrong, so the user cannot miss it \
while approving.";
/// Platform note appended to the prompt, so the agent writes local paths the
/// way the machine CrabPort runs on expects — on Windows that means `C:\...`
/// style paths for read_file / read_directory and the local side of the SFTP
/// transfers. Conditionally compiled: the note exists only when it is true.
#[cfg(windows)]
const PLATFORM_NOTE: &str = "\n\nNote: CrabPort itself is running on Windows, so \
every *local* path you use — read_file, read_directory, and the local side \
of sftp_download / sftp_upload — must be Windows-style, e.g. C:\\Users\\... . \
Remote paths follow the remote host's operating system.";
#[cfg(not(windows))]
const PLATFORM_NOTE: &str = "\n\nNote: CrabPort itself is running on a Unix-like \
system, so every *local* path you use — read_file, read_directory, and the \
local side of sftp_download / sftp_upload — is POSIX-style, e.g. /home/... . \
Remote paths follow the remote host's operating system.";
/// The pinned system prompt: base rules plus the platform note.
pub fn system_prompt() -> String {
format!("{BASE_PROMPT}{PLATFORM_NOTE}")
}
# ===== file: crabport-agent/src/session.rs =====
//! What the agent's tools need from a terminal session, and what the UI side
//! provides for it.
//!
//! The trait is deliberately context-free — no GPUI app handle, no entity
//! reads. A UI implements it as a cheap snapshot taken when a tool call is
//! approved: the shared session/backend handles, the directory the shell last
//! reported, an event subscription for transfer completions, the
//! Tunnels-page registry, and a channel that routes registry mutations back to
//! the UI thread (where the app's own tunnel machinery lives). That is what
//! lets [`crate::Agent`] run its work — including the polling loops — on
//! background threads, with the UI only awaiting the result.
use std::sync::Arc;
use std::time::Duration;
use async_broadcast::Receiver;
use crabport_sftp::FileEntry;
use crabport_ssh::{TunnelKind, TunnelManager};
use crabport_terminal::terminal::{BackendEvent, ExecCallback, ExecCancel, ExecOutput};
/// Snapshot of one Tunnels-page config, scoped by the UI to the session's
/// host. The agent reports these and may start/stop/delete them; it never
/// sees another host's (let alone another terminal's) tunnels.
#[derive(Clone)]
pub struct RegistryTunnel {
pub id: i64,
pub name: String,
pub kind: TunnelKind,
pub bind_addr: String,
pub bind_port: u16,
pub target_host: String,
pub target_port: u16,
pub running: bool,
/// `true` when the run borrows a terminal's connection (as opposed to a
/// dedicated one started from the Tunnels page).
pub borrowed: bool,
}
/// A terminal session as the agent's tools see it.
pub trait AgentSession: Send + Sync {
/// Whether out-of-band commands can run here (`terminal_exec`).
fn allow_exec_capture(&self) -> bool {
false
}
/// Whether this session supports SFTP (`sftp_*`).
fn allow_sftp(&self) -> bool {
false
}
/// Whether this session can host tunnels — an SSH connection is required.
fn allow_tunnels(&self) -> bool {
false
}
/// The directory the shell last reported, when shell integration says.
fn cwd(&self) -> Option<String> {
None
}
/// The host this session is connected to, when it came from a saved host.
fn host_id(&self) -> Option<i64> {
None
}
/// The most recent terminal output lines (scrollback + visible screen).
fn dump_text(&self, _lines: usize) -> String {
String::new()
}
/// Non-blocking [`Self::dump_text`]: `None` while the terminal reader
/// holds its lock — the caller retries on its next tick.
fn try_dump_text(&self, _lines: usize) -> Option<String> {
None
}
/// Type raw bytes into the interactive shell — the visible run's input.
fn write_raw(&self, _data: &[u8]) {}
/// Start an out-of-band command. `done` runs exactly once, on a
/// backend-owned thread; `cancel` stops the command when the user asks.
fn exec_capture(
&self,
_command: &str,
_timeout: Duration,
_cancel: ExecCancel,
done: ExecCallback,
) {
done(ExecOutput {
output: "captured execution is not supported on this connection".to_string(),
..Default::default()
});
}
/// The backend's event stream. The SFTP transfer tools subscribe *before*
/// starting a transfer: its `SftpTransferFinished` event is the only
/// completion signal there is.
fn subscribe_events(&self) -> Option<Receiver<BackendEvent>> {
None
}
/// The resolved remote directory and its listing, once a navigation has
/// landed. The `Arc` identity is the freshness signal: the backend
/// installs a new one on every successful read_dir.
fn sftp_listing(&self) -> Option<(String, Arc<Vec<FileEntry>>)> {
None
}
/// Ask the backend to list `path`; the result lands in
/// [`Self::sftp_listing`].
fn sftp_navigate(&self, _path: &str) {}
/// Start a download / upload. Completion shows up as a
/// [`BackendEvent::SftpTransferFinished`] on [`Self::subscribe_events`].
fn sftp_download(&self, _remote_path: &str, _local_path: &str) {}
fn sftp_upload(&self, _local_path: &str, _remote_path: &str) {}
/// This session's tunnel manager — one per session, created by the UI so
/// the agent's tunnels ride this connection and no other.
fn tunnel_manager(&self) -> Option<Arc<TunnelManager>> {
None
}
/// Tunnels configured for this session's host (running or stopped).
fn registry_tunnels(&self) -> Vec<RegistryTunnel> {
Vec::new()
}
fn registry_is_running(&self, _config_id: i64) -> bool {
false
}
/// Live addresses of a running registry tunnel:
/// `(bind_addr, bind_port, target_host, target_port)`.
fn registry_live(&self, _config_id: i64) -> Option<(String, u16, String, u16)> {
None
}
/// Ask the UI to start a registry tunnel borrowing this session, and to
/// stop / delete one. The UI routes these through the app's own tunnel
/// machinery, so the Tunnels page and the store stay consistent.
fn registry_open(&self, _config_id: i64) {}
fn registry_close(&self, _config_id: i64) {}
fn registry_delete(&self, _config_id: i64) {}
}
# ===== file: crabport-agent/src/sftp.rs =====
//! SFTP tool helpers: rendering a remote directory listing for the model.
use rust_i18n::t;
use crate::agent::ToolOutcome;
use crate::limits::READ_DIR_LIMIT;
/// Format a remote SFTP directory listing: one table row per entry
/// (name / type / size / permissions, as the model sees them), capped at
/// [`READ_DIR_LIMIT`].
pub fn format_remote_listing(entries: &[crabport_sftp::FileEntry]) -> ToolOutcome {
let rows: Vec<Vec<String>> = entries
.iter()
.take(READ_DIR_LIMIT)
.map(|entry| {
vec![
entry.name.clone(),
if entry.is_dir { "dir" } else { "file" }.to_string(),
entry
.size
.map(|bytes| bytes.to_string())
.unwrap_or_else(|| "-".to_string()),
entry.permissions.clone().unwrap_or_else(|| "-".to_string()),
]
})
.collect();
if rows.is_empty() {
return ToolOutcome::text(t!("ai_panel.tool_dir_empty"));
}
let mut outcome = ToolOutcome::table(&["name", "type", "size", "permissions"], rows);
if entries.len() > READ_DIR_LIMIT {
outcome.text.push_str(&format!(
"\n{}",
t!(
"ai_panel.tool_dir_truncated",
more = entries.len() - READ_DIR_LIMIT
)
));
}
outcome
}
#[cfg(test)]
mod tests {
use super::format_remote_listing;
/// A remote listing carries one row per entry with the kind marked and
/// sizes/permissions where known; the model's copy is JSON.
#[test]
fn format_remote_listing_marks_dirs_and_sizes() {
let entry = |name: &str, is_dir: bool, size: Option<u64>| crabport_sftp::FileEntry {
name: name.to_string(),
is_dir,
size,
permissions: None,
modified: None,
};
let outcome =
format_remote_listing(&[entry("src", true, None), entry("a.txt", false, Some(12))]);
assert!(outcome.text.contains(r#""name":"src""#), "{}", outcome.text);
assert!(outcome.text.contains(r#""type":"dir""#), "{}", outcome.text);
assert!(outcome.text.contains(r#""size":"12""#), "{}", outcome.text);
let table = outcome.table.expect("table present");
assert_eq!(table.headers, ["name", "type", "size", "permissions"]);
assert_eq!(table.rows.len(), 2);
assert_eq!(table.rows[0][1], "dir");
}
}
# ===== file: crabport-agent/src/shell.rs =====
//! Shell text helpers shared by the execution tools.
/// Prefix a captured command with `cd <dir> &&` when the shell has reported
/// its directory.
///
/// An out-of-band command starts in the login shell's directory (usually
/// `$HOME`), not where the user's terminal is — so without this a `ls` would
/// list the wrong directory. A visible run needs no prefix: it is typed into
/// the very shell the user is looking at.
pub fn with_cwd(command: &str, cwd: Option<&str>) -> String {
match cwd {
Some(dir) if !dir.is_empty() => format!("cd {} && {}", quote_shell(dir), command),
_ => command.to_string(),
}
}
/// Single-quote `text` for a POSIX shell, closing and reopening around
/// embedded quotes (`'` → `'\''`). Enough for the directory names
/// interpolated here, and the same quoting a user would expect from a shell.
pub fn quote_shell(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\\''"))
}
#[cfg(test)]
mod tests {
use super::{quote_shell, with_cwd};
/// A captured command starts where the user's terminal is, not in the
/// login shell's default directory — and paths with quotes/quotes-spaces
/// must survive the interpolation.
#[test]
fn with_cwd_prefixes_quoted_directory() {
assert_eq!(with_cwd("ls", None), "ls");
assert_eq!(with_cwd("ls", Some("")), "ls");
assert_eq!(with_cwd("ls", Some("/var/log")), "cd '/var/log' && ls");
assert_eq!(
with_cwd("cat file", Some("/tmp/it's here")),
"cd '/tmp/it'\\''s here' && cat file"
);
}
#[test]
fn quote_shell_escapes_single_quotes() {
assert_eq!(quote_shell("plain"), "'plain'");
assert_eq!(quote_shell("a'b"), "'a'\\''b'");
}
}
# ===== file: crabport-agent/src/text.rs =====
//! Truncation rules for tool results: what goes back to the model when a
//! command, file or HTTP body is bigger than the conversation should carry.
use crate::limits::MAX_TOOL_RESULT_BYTES;
/// The part of `after` that appeared since `before`, used to answer an
/// `execute` call with the command's own output instead of the whole screen.
///
/// Terminals scroll, so the interesting text is the suffix the two dumps
/// don't share; the common prefix is computed on bytes and then walked back
/// to a char boundary so the slice can't panic on multi-byte output. The
/// result is capped at [`MAX_TOOL_RESULT_BYTES`] (keeping the tail, which is
/// where the interesting part of a long output lives) so a chatty command
/// can't blow up the conversation's context.
pub fn new_since(before: &str, after: &str) -> String {
let before = before.as_bytes();
let after_bytes = after.as_bytes();
let mut ix = 0;
while ix < before.len() && ix < after_bytes.len() && before[ix] == after_bytes[ix] {
ix += 1;
}
while ix > 0 && !after.is_char_boundary(ix) {
ix -= 1;
}
cap_tool_result(after[ix..].trim_matches('\n'))
}
/// Cap a tool result at [`MAX_TOOL_RESULT_BYTES`], keeping the tail (where a
/// command's errors and summary usually are) and noting how much was dropped.
/// The cut is walked to a char boundary so the slice can't panic on
/// multi-byte output.
pub fn cap_tool_result(text: &str) -> String {
if text.len() <= MAX_TOOL_RESULT_BYTES {
return text.to_string();
}
let mut cut = text.len() - MAX_TOOL_RESULT_BYTES;
while cut < text.len() && !text.is_char_boundary(cut) {
cut += 1;
}
format!("(earlier output omitted — {} bytes)\n{}", cut, &text[cut..])
}
/// Cap a tool result at [`MAX_TOOL_RESULT_BYTES`] keeping the *head* — used
/// where the beginning of the text is the interesting part (HTTP bodies, file
/// contents) — and note how much was dropped. The cut is walked back to a
/// char boundary so the slice can't panic on multi-byte output.
pub fn cap_tool_result_head(text: &str) -> String {
if text.len() <= MAX_TOOL_RESULT_BYTES {
return text.to_string();
}
let mut end = MAX_TOOL_RESULT_BYTES;
while end > 0 && !text.is_char_boundary(end) {
end -= 1;
}
format!(
"{}\n(later output omitted — {} bytes)",
&text[..end],
text.len() - end
)
}
#[cfg(test)]
mod tests {
use super::{cap_tool_result, cap_tool_result_head};
use crate::limits::MAX_TOOL_RESULT_BYTES;
#[test]
fn cap_tool_result_keeps_the_tail_on_a_char_boundary() {
let short = "hello";
assert_eq!(cap_tool_result(short), short);
// Multi-byte output longer than the cap: the cut must not split a
// char, and it must land near the end.
let long = "⇒".repeat(MAX_TOOL_RESULT_BYTES);
let capped = cap_tool_result(&long);
assert!(capped.len() < long.len());
assert!(capped.starts_with("(earlier output omitted"));
assert!(capped.ends_with("⇒"));
}
/// The head-keeping cap is for HTTP bodies and file contents: the
/// beginning survives, the dropped amount is noted, and multi-byte
/// output is never split.
#[test]
fn cap_tool_result_head_keeps_the_front_on_a_char_boundary() {
let short = "hello";
assert_eq!(cap_tool_result_head(short), short);
let long = "⇒".repeat(MAX_TOOL_RESULT_BYTES * 2);
let capped = cap_tool_result_head(&long);
assert!(capped.len() < long.len());
assert!(capped.contains("(later output omitted"));
assert!(capped.starts_with("⇒"));
}
}
# ===== file: crabport-agent/src/tools.rs =====
//! The advertised tool specs and their wire-name metadata. Stable names —
//! conversations replay them, and everything else dispatches on [`ToolKind`].
use crabport_ai::ToolSpec;
/// Every tool name the agent advertises, in definition order.
///
/// For surfaces that only need to *enumerate* the tools — the settings
/// pane's per-tool permission list — without building the JSON schemas.
/// Kept in sync with [`agent_tools`] by a test.
pub const TOOL_NAMES: &[&str] = &[
"terminal_read",
"terminal_exec",
"terminal_run",
"read_file",
"read_directory",
"fetch",
"tunnel_create",
"tunnel_list",
"tunnel_open",
"tunnel_close",
"tunnel_delete",
"sftp_list",
"sftp_download",
"sftp_upload",
];
/// Tools advertised to the model. Names are stable — the wire history replays
/// them, and the panel dispatches on them in [`ToolKind::of`].
pub fn agent_tools() -> Vec<ToolSpec> {
vec![
ToolSpec::new(
"terminal_read",
"Read the most recent lines of this terminal's output (scrollback + \
visible screen). Use it to see command results, error messages, or \
what the user is looking at before answering.",
serde_json::json!({
"type": "object",
"properties": {
"lines": {
"type": "integer",
"description": "How many of the most recent lines to read (1-500)."
},
"purpose": {
"type": "string",
"description": "Why you need this output — shown to the user for approval."
}
},
"required": ["lines", "purpose"]
}),
),
ToolSpec::new(
"terminal_exec",
"Run one command out of band and return its captured stdout + stderr \
and exit code. This is the default execution tool: the command does \
not appear in the user's terminal and has no tty, so anything \
interactive (prompts, pagers, editors) will fail or time out \
instead of waiting forever. Use terminal_run only when the output \
must stream where the user can watch it, or the command needs to \
prompt for input.",
serde_json::json!({
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The exact command line to run."
},
"expected": {
"type": "string",
"description": "What you expect this command to do — shown to the user for approval."
}
},
"required": ["command", "expected"]
}),
),
ToolSpec::new(
"terminal_run",
"Type one command line into the user's live terminal, exactly as if \
the user typed it and pressed Enter, and return the output that \
appears. Use it only for long-running, streaming or interactive \
commands (dev servers, log tails, builds, REPLs, anything that \
may prompt for input such as sudo) — otherwise prefer \
terminal_exec.",
serde_json::json!({
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The exact command line to run."
},
"expected": {
"type": "string",
"description": "What you expect this command to do — shown to the user for approval."
}
},
"required": ["command", "expected"]
}),
),
ToolSpec::new(
"read_file",
"Read one file on the machine CrabPort itself runs on — the local \
machine, never the remote host. Use it for files the user \
mentions, or that a fetch/command produced locally.",
serde_json::json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Local path of the file to read."
},
"purpose": {
"type": "string",
"description": "Why you need it — shown to the user for approval."
}
},
"required": ["path", "purpose"]
}),
),
ToolSpec::new(
"read_directory",
"List one directory on the machine CrabPort itself runs on — the \
local machine, never the remote host. Returns names, types and \
sizes, not file contents.",
serde_json::json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Local path of the directory to list."
},
"purpose": {
"type": "string",
"description": "Why you need it — shown to the user for approval."
}
},
"required": ["path", "purpose"]
}),
),
ToolSpec::new(
"fetch",
"Send one HTTP request from inside CrabPort and return the status, \
response headers and body. It runs on the local machine's \
network, not the remote host's — pass a proxy URL to route it \
elsewhere. To reach an address only the remote host can reach, \
first create and open a dynamic tunnel on this session, then pass \
its proxy as socks5h://127.0.0.1:<port> (the h matters: the \
hostname is then resolved on the remote side).",
serde_json::json!({
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "Absolute URL to request."
},
"method": {
"type": "string",
"enum": ["GET", "POST", "PUT", "DELETE", "HEAD"],
"description": "HTTP method; defaults to GET."
},
"body": {
"type": "string",
"description": "Request body, for POST/PUT."
},
"proxy": {
"type": "string",
"description": "Optional proxy URL, e.g. socks5h://127.0.0.1:1080 from a dynamic tunnel."
},
"expected": {
"type": "string",
"description": "What you expect this request to do — shown to the user for approval."
}
},
"required": ["url", "expected"]
}),
),
ToolSpec::new(
"tunnel_create",
"Define a *temporary* tunnel on the current tab's SSH connection \
(not started yet; no extra connection is opened — tunnels ride \
the tab's session). It lives only in this conversation: it is \
never persisted, the Tunnels page never shows it, and it is gone \
when this terminal closes. For a persistent tunnel, ask the user \
to create it in the Tunnels page instead. Kinds: local forwards a \
local port to a remote target; dynamic opens a SOCKS5 proxy on a \
local port (no target — each client picks the destination per \
connection); remote asks the remote server to listen and forward \
back to this machine.",
serde_json::json!({
"type": "object",
"properties": {
"kind": {
"type": "string",
"enum": ["local", "dynamic", "remote"],
"description": "Tunnel type."
},
"name": {
"type": "string",
"description": "Short name for the tunnel."
},
"bind_port": {
"type": "integer",
"description": "Port to listen on; 0 picks a free one."
},
"target_host": {
"type": "string",
"description": "Forward target host — required for local/remote, ignored for dynamic."
},
"target_port": {
"type": "integer",
"description": "Forward target port — required for local/remote, ignored for dynamic."
},
"expected": {
"type": "string",
"description": "What you expect the tunnel to be used for — shown to the user for approval."
}
},
"required": ["kind", "name", "expected"]
}),
),
ToolSpec::new(
"tunnel_list",
"List the tunnels available on this tab: the ones you created here \
(ids starting with a), plus the Tunnels-page configs bound to this \
tab's host (ids starting with t) — running or stopped. Both id \
kinds work with tunnel_open / tunnel_close / tunnel_delete.",
serde_json::json!({
"type": "object",
"properties": {},
"required": []
}),
),
ToolSpec::new(
"tunnel_open",
"Start a tunnel and get back the address it listens on. Use an id \
token from tunnel_list / tunnel_create: `a…` is a tunnel you \
created in this session, `t…` is a Tunnels-page config bound to \
this host (opening it borrows the tab's SSH connection).",
serde_json::json!({
"type": "object",
"properties": {
"tunnel_id": {
"type": "string",
"description": "Id token as returned by tunnel_list / tunnel_create (a… or t…)."
},
"expected": {
"type": "string",
"description": "What you expect this to do — shown to the user for approval."
}
},
"required": ["tunnel_id", "expected"]
}),
),
ToolSpec::new(
"tunnel_close",
"Stop a running tunnel. Its port stops listening; existing \
connections are torn down. Id tokens from tunnel_list: `a…` for \
tunnels you created, `t…` for Tunnels-page configs on this host.",
serde_json::json!({
"type": "object",
"properties": {
"tunnel_id": {
"type": "string",
"description": "Id token as returned by tunnel_list / tunnel_create (a… or t…)."
},
"expected": {
"type": "string",
"description": "What you expect this to do — shown to the user for approval."
}
},
"required": ["tunnel_id", "expected"]
}),
),
ToolSpec::new(
"tunnel_delete",
"Delete a tunnel — stopping it first when it is running. `a…` \
tokens delete tunnels you created here; `t…` tokens delete the \
Tunnels-page config itself.",
serde_json::json!({
"type": "object",
"properties": {
"tunnel_id": {
"type": "string",
"description": "Id token as returned by tunnel_list / tunnel_create (a… or t…)."
},
"expected": {
"type": "string",
"description": "What you expect this to do — shown to the user for approval."
}
},
"required": ["tunnel_id", "expected"]
}),
),
ToolSpec::new(
"sftp_list",
"List one directory on the remote host over this session's SFTP \
connection: names, types, sizes. Note that this also moves the \
SFTP panel's view to that directory.",
serde_json::json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Remote directory to list."
},
"purpose": {
"type": "string",
"description": "Why you need it — shown to the user for approval."
}
},
"required": ["path", "purpose"]
}),
),
ToolSpec::new(
"sftp_download",
"Download one file from the remote host to a local path, over this \
session's SFTP connection. The local path lives on the machine \
CrabPort runs on.",
serde_json::json!({
"type": "object",
"properties": {
"remote_path": {
"type": "string",
"description": "Path of the file on the remote host."
},
"local_path": {
"type": "string",
"description": "Destination path on the local machine."
},
"purpose": {
"type": "string",
"description": "Why you need it — shown to the user for approval."
}
},
"required": ["remote_path", "local_path", "purpose"]
}),
),
ToolSpec::new(
"sftp_upload",
"Upload one local file to the remote host, over this session's \
SFTP connection. The local path lives on the machine CrabPort \
runs on.",
serde_json::json!({
"type": "object",
"properties": {
"local_path": {
"type": "string",
"description": "Path of the file on the local machine."
},
"remote_path": {
"type": "string",
"description": "Destination path on the remote host."
},
"purpose": {
"type": "string",
"description": "Why you need it — shown to the user for approval."
}
},
"required": ["local_path", "remote_path", "purpose"]
}),
),
]
}
/// Which agent tool a call names. The names are the wire contract with the
/// model, so they are mapped in exactly one place.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ToolKind {
/// `terminal_read` — snapshot of the recent screen, answered inline.
TerminalRead,
/// `terminal_exec` — run out of band, output captured directly.
ExecCapture,
/// `terminal_run` — typed into the live terminal, output read from the
/// screen once it settles.
Run,
/// `fetch` — one HTTP request from inside CrabPort, optional proxy.
Fetch,
/// `read_file` / `read_directory` — the local filesystem.
LocalFs,
/// `tunnel_create` / `tunnel_open` / `tunnel_close` / `tunnel_delete`.
Tunnel,
/// `sftp_list` / `sftp_download` / `sftp_upload`.
Sftp,
/// Anything else the model invented; refused with a readable error.
Unknown,
}
impl ToolKind {
pub fn of(name: &str) -> Self {
match name {
"terminal_read" => Self::TerminalRead,
"terminal_exec" => Self::ExecCapture,
"terminal_run" => Self::Run,
"fetch" => Self::Fetch,
"read_file" | "read_directory" => Self::LocalFs,
name if name.starts_with("tunnel_") => Self::Tunnel,
name if name.starts_with("sftp_") => Self::Sftp,
_ => Self::Unknown,
}
}
}
#[cfg(test)]
mod tests {
use super::{TOOL_NAMES, ToolKind, agent_tools};
/// The name list the settings pane enumerates matches the advertised
/// specs exactly — a tool added to one and not the other would silently
/// lose its permission row (or list a tool that doesn't exist).
#[test]
fn tool_names_match_agent_tools() {
let advertised: Vec<String> = agent_tools().into_iter().map(|spec| spec.name).collect();
assert_eq!(TOOL_NAMES, advertised.as_slice());
}
#[test]
fn tool_kind_maps_wire_names() {
assert_eq!(ToolKind::of("terminal_read"), ToolKind::TerminalRead);
assert_eq!(ToolKind::of("terminal_exec"), ToolKind::ExecCapture);
assert_eq!(ToolKind::of("terminal_run"), ToolKind::Run);
assert_eq!(ToolKind::of("terminal_execute"), ToolKind::Unknown);
assert_eq!(ToolKind::of("fetch"), ToolKind::Fetch);
assert_eq!(ToolKind::of("read_file"), ToolKind::LocalFs);
assert_eq!(ToolKind::of("read_directory"), ToolKind::LocalFs);
assert_eq!(ToolKind::of("tunnel_create"), ToolKind::Tunnel);
assert_eq!(ToolKind::of("tunnel_open"), ToolKind::Tunnel);
assert_eq!(ToolKind::of("tunnel_close"), ToolKind::Tunnel);
assert_eq!(ToolKind::of("tunnel_delete"), ToolKind::Tunnel);
assert_eq!(ToolKind::of("sftp_list"), ToolKind::Sftp);
assert_eq!(ToolKind::of("sftp_download"), ToolKind::Sftp);
assert_eq!(ToolKind::of("sftp_upload"), ToolKind::Sftp);
assert_eq!(ToolKind::of("sftp_delete"), ToolKind::Sftp);
}
}
# ===== file: crabport-agent/src/tunnel.rs =====
//! The agent's tunnel model: a *session-local* definition owned by one
//! conversation, with the id tokens (`a<N>`) the model refers to.
use std::sync::Arc;
use rust_i18n::t;
use crabport_ssh::{TunnelId, TunnelKind, TunnelManager};
/// One tunnel the agent defined through this terminal's connection.
///
/// Agent-facing ids are stable and never reused (a delete keeps its slot),
/// so a `tunnel_open` the model issues later cannot hit the wrong tunnel.
/// The tunnels live in the panel's own [`TunnelManager`] — scoped to this
/// terminal's connection, invisible to every other tab.
#[derive(Clone)]
pub(crate) struct AgentTunnel {
pub(crate) agent_id: u64,
pub(crate) kind: TunnelKind,
pub(crate) name: String,
pub(crate) bind_addr: String,
pub(crate) bind_port: u16,
pub(crate) target_host: String,
pub(crate) target_port: u16,
pub(crate) state: AgentTunnelState,
}
/// Lifecycle of an agent-created tunnel.
#[derive(Clone)]
pub(crate) enum AgentTunnelState {
/// Defined, not started.
Created,
/// Started; carries the manager's tunnel id.
Running(TunnelId),
/// Stopped — the manager's entry is gone. Can be opened again.
Closed,
/// The last open attempt failed, with the reason.
Failed(String),
/// Deleted. Kept in the list so earlier ids stay valid.
Deleted,
}
impl AgentTunnel {
/// The token the agent refers to this tunnel by — `a<agent_id>`, so it
/// can never collide with a Tunnels-page config id (`t<db id>`).
pub(crate) fn handle(&self) -> String {
format!("a{}", self.agent_id)
}
/// The full address pair of this tunnel — `bind -> target` for local and
/// remote tunnels (the model needs both ends), just the bind port for
/// dynamic ones (whose target is picked per connection). `0` as a bind
/// port means "unused / pick a free one at open".
pub(crate) fn addresses(&self) -> String {
let mut out = format!("{}:{}", self.bind_addr, self.bind_port);
if self.kind != TunnelKind::Dynamic && !self.target_host.is_empty() && self.target_port != 0
{
out.push_str(&format!(" -> {}:{}", self.target_host, self.target_port));
}
out
}
/// One-line description for cards and results.
pub(crate) fn describe(&self, manager: Option<&Arc<TunnelManager>>) -> String {
let base = format!("{} {} ({})", self.handle(), self.name, self.kind.as_str());
match &self.state {
AgentTunnelState::Created => {
format!("{base} — created, not started ({})", self.addresses())
}
AgentTunnelState::Closed => format!("{base} — closed ({})", self.addresses()),
AgentTunnelState::Deleted => format!("{base} — deleted ({})", self.addresses()),
AgentTunnelState::Failed(reason) => {
format!("{base} — open failed: {reason} ({})", self.addresses())
}
AgentTunnelState::Running(id) => match manager.and_then(|m| m.get(*id)) {
Some(info) => {
let mut text = format!(
"{base} — {}",
t!(
"ai_panel.tunnel_running_at",
bind = format!("{}:{}", info.bind_addr, info.bind_port)
)
);
if !info.target_host.is_empty() && info.target_port != 0 {
text.push_str(&format!(" -> {}:{}", info.target_host, info.target_port));
}
text
}
None => format!("{base} — running ({})", self.addresses()),
},
}
}
/// One labelled row of the `tunnel_list` table: id / name / kind /
/// address / status. The id token leads — it is what the open / close /
/// delete calls take.
pub(crate) fn list_row(&self, manager: Option<&Arc<TunnelManager>>) -> Vec<String> {
let mut address = self.addresses();
let status = match &self.state {
AgentTunnelState::Running(id) => {
if let Some(info) = manager.and_then(|manager| manager.get(*id)) {
address = format!("{}:{}", info.bind_addr, info.bind_port);
if !info.target_host.is_empty() && info.target_port != 0 {
address.push_str(&format!(" -> {}:{}", info.target_host, info.target_port));
}
}
t!("ai_panel.tunnel_state_running")
}
AgentTunnelState::Created => t!("ai_panel.tunnel_state_created"),
AgentTunnelState::Closed => t!("ai_panel.tunnel_state_closed"),
AgentTunnelState::Deleted => t!("ai_panel.tunnel_state_deleted"),
AgentTunnelState::Failed(_) => t!("ai_panel.tunnel_state_failed"),
};
vec![
self.handle(),
self.name.clone(),
self.kind.as_str().to_string(),
address,
status.to_string(),
]
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The `tunnel_list` row: the actionable id token first, kind and
/// addresses next, and the state word last; a running tunnel reports the
/// *actual* listen address from the manager when it has one.
#[test]
fn list_row_carries_token_kind_address_status() {
let tunnel = AgentTunnel {
agent_id: 3,
kind: TunnelKind::Local,
name: "db".to_string(),
bind_addr: "127.0.0.1".to_string(),
bind_port: 15432,
target_host: "db.internal".to_string(),
target_port: 5432,
state: AgentTunnelState::Created,
};
let row = tunnel.list_row(None);
assert_eq!(row[0], "a3");
assert_eq!(row[1], "db");
assert_eq!(row[2], "local");
assert!(row[3].contains("127.0.0.1:15432"), "{}", row[3]);
assert!(row[3].contains("db.internal:5432"), "{}", row[3]);
assert!(!row[4].is_empty());
}
}
# ===== file: crabport-ai/src/error.rs =====
//! Error type shared across the AI layer.
//!
//! Hand-rolled `Display`/`Error` impls instead of `thiserror` — matches
//! the rest of the workspace (`crabport_core::StoreError`) and keeps the
//! dependency tree flat.
use std::fmt;
/// Errors surfaced by [`crate::provider::ChatProvider`] implementations.
#[derive(Debug)]
pub enum AiError {
/// Connection / DNS / TLS level failure or a connect timeout.
Network(String),
/// The remote API answered with a non-success HTTP status. `message`
/// carries the server-provided error text when available.
Api { status: u16, message: String },
/// The server answered 200 but produced unparseable output (bad JSON,
/// broken SSE framing, oversized lines, …).
Protocol(String),
/// Local I/O failure while reading the response body.
Io(std::io::Error),
/// The consumer dropped/closed the event channel; the worker stopped
/// early. Not a fault.
Cancelled,
}
impl fmt::Display for AiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AiError::Network(m) => write!(f, "network error: {m}"),
AiError::Api { status, message } => write!(f, "api error ({status}): {message}"),
AiError::Protocol(m) => write!(f, "protocol error: {m}"),
AiError::Io(e) => write!(f, "io error: {e}"),
AiError::Cancelled => write!(f, "stream cancelled"),
}
}
}
impl std::error::Error for AiError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
AiError::Io(e) => Some(e),
_ => None,
}
}
}
impl From<std::io::Error> for AiError {
fn from(e: std::io::Error) -> Self {
AiError::Io(e)
}
}
# ===== file: crabport-ai/src/lib.rs =====
//! crabport-ai — LLM chat/streaming layer for CrabPort.
//!
//! Architecture:
//!
//! * [`types`] — provider-neutral conversation types ([`ChatMessage`],
//! [`ToolCall`], [`ChatRequest`], …) plus the [`StreamEvent`] deltas a
//! completion emits while it runs.
//! * [`provider`] — the [`ChatProvider`] contract. Blocking by design:
//! implementations pump events into an `async_channel::Sender` until the
//! stream ends, then return the fully-assembled [`ChatResponse`].
//! * [`openai`] — OpenAI-compatible provider built on the
//! [`async-openai`](https://docs.rs/async-openai) crate: request
//! serialization, SSE stream parsing and API error mapping are delegated
//! to the library; this module only translates between its chat types and
//! the provider-neutral ones above.
//! * [`spawn_chat_stream`] — runs a provider call on a dedicated worker
//! thread and exposes the event flow as plain async channels, so GPUI
//! views can await it from `cx.spawn` without importing a tokio runtime.
//!
//! The crate deliberately stays UI-free and storage-free: provider
//! credentials and settings live in `crabport-core` / the settings view;
//! this crate only knows how to talk to an API once handed a key.
pub mod error;
pub mod openai;
pub mod provider;
pub mod types;
use std::sync::Arc;
use async_channel::Receiver;
pub use error::AiError;
pub use openai::{ModelInfo, OpenAiProvider};
pub use provider::ChatProvider;
pub use types::{
ChatMessage, ChatRequest, ChatResponse, FinishReason, MESSAGE_OVERHEAD_TOKENS, Role,
StreamEvent, TOOL_CALL_OVERHEAD_TOKENS, TokenUsage, ToolCall, ToolSpec, estimate_tokens,
};
/// Live handle to a completion running on the worker thread.
///
/// Cloning shares the same channels: any clone can [`ChatStream::cancel`]
/// the stream, and awaiting through one clone while another cancels is the
/// intended split (the chat panel keeps a handle for its Stop button while
/// the pump task awaits a clone).
///
/// Dropping the handle does not abort the worker immediately; call
/// [`ChatStream::cancel`] to close the event channel — the worker detects
/// it on its next send and unwinds with [`AiError::Cancelled`].
#[derive(Clone)]
pub struct ChatStream {
events: Receiver<StreamEvent>,
done: Receiver<Result<ChatResponse, AiError>>,
}
impl ChatStream {
/// Await the next [`StreamEvent`]; returns `None` once the stream has
/// ended (then read the final outcome via [`Self::result`]).
pub async fn next_event(&self) -> Option<StreamEvent> {
self.events.recv().await.ok()
}
/// Await the final outcome. Resolves when the worker finished;
/// typically called right after [`Self::next_event`] returned `None`.
pub async fn result(&self) -> Result<ChatResponse, AiError> {
self.done.recv().await.unwrap_or(Err(AiError::Cancelled))
}
/// Cancel the stream early. Closes both channels: the worker observes
/// the closed event channel on its next send and stops with
/// [`AiError::Cancelled`], and its final-result send resolves instantly
/// instead of blocking a worker thread on an unread outcome.
pub fn cancel(&self) {
self.events.close();
self.done.close();
}
}
/// Run `provider.complete_stream(&request)` on a dedicated worker thread.
///
/// Returns immediately. Streamed deltas arrive via
/// [`ChatStream::next_event`]; the assembled response via
/// [`ChatStream::result`]. Events are buffered (capacity 64) so short
/// token bursts don't stall the network reader.
pub fn spawn_chat_stream(provider: Arc<dyn ChatProvider>, request: ChatRequest) -> ChatStream {
let (events_tx, events_rx) = async_channel::bounded(64);
let (done_tx, done_rx) = async_channel::bounded(1);
std::thread::Builder::new()
.name("crabport-ai-stream".into())
.spawn(move || {
let outcome = provider.complete_stream(&request, &events_tx);
events_tx.close();
let _ = done_tx.send_blocking(outcome);
})
.expect("failed to spawn crabport-ai worker thread");
ChatStream {
events: events_rx,
done: done_rx,
}
}
# ===== file: crabport-ai/src/openai.rs =====
//! OpenAI-compatible chat provider backed by the [`async_openai`] crate.
//!
//! Wire-format concerns are split by maturity: request serialization and
//! SSE stream parsing are delegated to `async-openai`, while streaming
//! chunk deserialization uses its `byot` (bring your own types) escape
//! hatch with tolerant local types — OpenAI-compatible servers routinely
//! deviate from the official schema (DeepSeek streams `reasoning_content`
//! and uses non-standard finish reasons), and the library's strict chunk
//! types would reject them. The async stream is driven to completion on a
//! current-thread tokio runtime owned by the calling worker thread (see
//! [`crate::spawn_chat_stream`]). GPUI never sees tokio.
use async_channel::Sender;
use async_openai::Client;
use async_openai::config::OpenAIConfig;
use async_openai::error::OpenAIError;
use async_openai::types::chat::{
ChatCompletionMessageToolCall, ChatCompletionMessageToolCalls,
ChatCompletionRequestAssistantMessageArgs, ChatCompletionRequestAssistantMessageContent,
ChatCompletionRequestMessage, ChatCompletionRequestSystemMessage,
ChatCompletionRequestSystemMessageContent, ChatCompletionRequestToolMessage,
ChatCompletionRequestToolMessageContent, ChatCompletionRequestUserMessage,
ChatCompletionRequestUserMessageContent, ChatCompletionTool, ChatCompletionTools,
CreateChatCompletionRequest, CreateChatCompletionRequestArgs, FunctionCall, FunctionObject,
};
use futures_util::StreamExt;
use secrecy::{ExposeSecret, SecretString};
use tokio::runtime::Builder as RuntimeBuilder;
use tracing::debug;
use crate::error::AiError;
use crate::provider::ChatProvider;
use crate::types::{
ChatMessage, ChatRequest, ChatResponse, FinishReason, Role, StreamEvent, TokenUsage, ToolCall,
ToolSpec,
};
/// Upper bound on distinct tool calls assembled within a single turn.
const MAX_TOOL_CALLS: usize = 64;
/// User agent sent with every request, identifying the client instead of
/// shipping a generic SDK name — what OpenCode's gateways ask for (see
/// <https://opencode.ai/docs/go/#where-can-i-use-it>).
const USER_AGENT: &str = concat!("CrabPort/", env!("CARGO_PKG_VERSION"));
/// Per-conversation routing header required by OpenCode's gateways: a chat
/// request without it is rejected with `MissingSessionID`. Other
/// OpenAI-compatible endpoints ignore it, so it is only attached when the
/// caller passes a session id.
pub const OPENCODE_SESSION_HEADER: &str = "x-opencode-session";
/// Blocking [`ChatProvider`] for any OpenAI-compatible endpoint.
///
/// Wraps an [`async_openai::Client`] configured with the endpoint's base
/// URL and API key; the model travels per-request via [`ChatRequest::model`]
/// so callers can switch models between turns without rebuilding the
/// provider.
pub struct OpenAiProvider {
client: Client<OpenAIConfig>,
}
impl OpenAiProvider {
/// Build a provider for any `/chat/completions`-speaking server.
///
/// `base_url` may carry a path prefix (e.g.
/// `https://api.deepseek.com/v1`); trailing slashes are normalized.
///
/// Construction is cheap but not free: it builds a fresh
/// `reqwest::Client` (and its connection pool), so hold the provider
/// for the app's lifetime and reuse it across turns — don't rebuild per
/// turn or per model switch (the model rides on [`ChatRequest`]).
pub fn new(base_url: &str, api_key: SecretString) -> Result<Self, AiError> {
Ok(Self {
client: Client::with_config(build_config(base_url, &api_key, None)?),
})
}
/// [`Self::new`] plus the conversation's session id, sent as
/// [`OPENCODE_SESSION_HEADER`] on every request.
///
/// OpenCode's gateways route chat traffic per conversation and reject
/// requests without the header (`api error (400): MissingSessionID`).
/// The id only has to be stable across one conversation's requests — a
/// fresh one per conversation is exactly right.
pub fn with_session(
base_url: &str,
api_key: SecretString,
session_id: &str,
) -> Result<Self, AiError> {
Ok(Self {
client: Client::with_config(build_config(base_url, &api_key, Some(session_id))?),
})
}
}
/// Client config for an OpenAI-compatible endpoint: base URL, key, the
/// CrabPort user agent, and — when the caller has one — the conversation
/// session id. Split out from the constructors so the exact header set is
/// testable without a live server.
fn build_config(
base_url: &str,
api_key: &SecretString,
session_id: Option<&str>,
) -> Result<OpenAIConfig, AiError> {
let base = base_url.trim().trim_end_matches('/');
if !base.starts_with("http://") && !base.starts_with("https://") {
return Err(AiError::Network(format!(
"base URL must start with http:// or https://: {base_url:?}"
)));
}
let mut config = OpenAIConfig::new()
.with_api_base(base)
.with_api_key(api_key.expose_secret())
.with_header("user-agent", USER_AGENT)
.map_err(|err| AiError::Network(format!("user-agent header rejected: {err}")))?;
if let Some(session_id) = session_id {
config = config
.with_header(OPENCODE_SESSION_HEADER, session_id)
.map_err(|err| AiError::Network(format!("session header rejected: {err}")))?;
}
Ok(config)
}
impl ChatProvider for OpenAiProvider {
fn complete_stream(
&self,
request: &ChatRequest,
events: &Sender<StreamEvent>,
) -> Result<ChatResponse, AiError> {
// Each call already runs on its own worker thread
// (`spawn_chat_stream`), so a private current-thread runtime is the
// cheapest way to drive the async HTTP + SSE machinery without
// leaking a tokio runtime into the UI layer.
let runtime = RuntimeBuilder::new_current_thread()
.enable_all()
.build()
.map_err(|err| AiError::Network(format!("tokio runtime: {err}")))?;
runtime.block_on(self.stream_turn(request, events))
}
}
impl OpenAiProvider {
/// Fetch the endpoint's model list (`GET {base}/models`).
///
/// Blocking: drives the async request on a private current-thread
/// runtime — the same contract as [`ChatProvider::complete_stream`],
/// so call it from a background task (`cx.spawn`), never the UI thread.
///
/// Uses the `byot` (bring your own type) escape hatch instead of the
/// library's strict `ListModelResponse`: OpenAI-compatible endpoints
/// frequently deviate from the official schema (e.g. DeepSeek omits
/// `Model::created` and adds `name` / `context_window` fields), so only
/// `data[].id` and an optional context window are extracted from the raw
/// JSON and everything else is ignored.
pub fn list_models(&self) -> Result<Vec<ModelInfo>, AiError> {
let runtime = RuntimeBuilder::new_current_thread()
.enable_all()
.build()
.map_err(|err| AiError::Network(format!("tokio runtime: {err}")))?;
runtime.block_on(async {
let value: serde_json::Value = self
.client
.models()
.list_by
# ===== file: build.rs =====
//! Build script for the main `CrabPort` binary.
//!
//! On Windows, embeds `app-icon.ico` into the final `.exe` so the OS shows
//! our icon in the taskbar, Alt-Tab switcher, and Explorer (instead of the
//! generic Rust exe icon). The icon is referenced from a tiny `.rc` resource
//! script compiled by `embed-resource`, which finds `rc.exe` from the Windows
//! SDK / MSVC toolchain automatically.
//!
//! On macOS and Linux this is a no-op — the platform bundles (`.app` /
//! `.AppImage`) carry the icon via `cargo-bundle` using
//! `[package.metadata.bundle].icon`, not via the binary itself.
//!
//! No version-sync check is needed here: `[workspace.package].version` is the
//! single source of truth, inherited by every member crate via
//! `version.workspace = true`. `cargo-bundle` reads the package version via
//! `cargo_metadata` (which resolves workspace inheritance), and since we
//! intentionally do NOT set `bundle.version`, it falls back to the package
//! version automatically — no duplication to drift out of sync.
#[cfg(target_os = "windows")]
fn main() {
// Re-run if the icon or rc file changes.
println!("cargo:rerun-if-changed=app-icon.ico");
println!("cargo:rerun-if-changed=crabport.rc");
embed_resource::compile("crabport.rc", embed_resource::NONE)
.manifest_optional()
.expect("failed to compile crabport.rc");
}
#[cfg(not(target_os = "windows"))]
fn main() {
// Re-run if the macOS Info.plist extension changes — it's merged
// into the generated Info.plist by `cargo-bundle`, but `cargo-bundle`
// runs outside of cargo's dependency tracking so we have to opt in.
println!("cargo:rerun-if-changed=Info.plist.ext");
}
# ===== file: crabport-agent/src/agent.rs =====
//! The agent's tool execution: one [`Agent`] per conversation runs the
//! advertised tools against an [`AgentSession`].
//!
//! Everything here is UI-free — the polling loops included. They run on
//! background threads via `smol`, and hand their result to the UI through an
//! [`Executed::Pending`] receiver; the UI only awaits and renders.
use std::sync::{Arc, Mutex};
use std::time::Instant;
use async_channel::{Receiver, bounded};
use rust_i18n::t;
use serde_json::Value;
use crabport_ssh::{TOKIO, TunnelKind, TunnelManager, TunnelStatus};
use crabport_terminal::terminal::{BackendEvent, ExecCancel, ExecOutput, SftpTransferKind};
use crate::limits::{
AGENT_READ_LINES, EXEC_CAPTURE_TIMEOUT, OUTPUT_POLL, OUTPUT_QUIET, OUTPUT_TIMEOUT,
SFTP_LIST_TIMEOUT, SFTP_TRANSFER_TIMEOUT, TUNNEL_START_TIMEOUT,
};
use crate::session::AgentSession;
use crate::sftp::format_remote_listing;
use crate::shell::with_cwd;
use crate::text::{cap_tool_result, new_since};
use crate::tools::ToolKind;
use crate::tunnel::{AgentTunnel, AgentTunnelState};
/// What one tool call produced.
#[derive(Clone, Default)]
pub struct ToolOutcome {
/// The text handed back to the model (the approval card renders it too).
pub text: String,
/// The tabular view of the result, when the result is an enumerable
/// list. The model's copy (in `text`) is the same cells as JSON; the card
/// renders the table natively instead of letting the model re-render
/// markdown over it.
pub table: Option<ToolTable>,
/// Exit status of a captured command, when the backend reported one.
pub exit_code: Option<u32>,
/// A captured command outlived its deadline; the output is what was
/// captured before that.
pub timed_out: bool,
/// The user stopped the call while it ran.
pub cancelled: bool,
}
/// A list-style tool result as labelled cells: what the panel renders as a
/// native table, and what the model receives as JSON objects keyed by the
/// headers.
#[derive(Clone, Debug)]
pub struct ToolTable {
pub headers: Vec<String>,
pub rows: Vec<Vec<String>>,
}
impl ToolOutcome {
/// An outcome that is plain text and nothing else.
pub fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),