1pub mod catalog;
8pub(crate) mod engine;
9pub mod handoff;
10pub(crate) mod pool;
11pub(crate) mod redactor;
12pub mod trust;
13pub mod verify_bridge;
14pub mod wire;
15
16use std::{fmt, path::PathBuf, str::FromStr};
17
18use serde::{Deserialize, Serialize};
19
20use crate::{
21 agent::error::{Code, Failure},
22 repository,
23};
24
25pub const MAX_AGENT_ID_BYTES: usize = 64;
27
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
30#[serde(transparent)]
31pub struct AgentId(String);
32
33impl AgentId {
34 pub fn as_str(&self) -> &str {
35 &self.0
36 }
37}
38
39impl FromStr for AgentId {
40 type Err = String;
41
42 fn from_str(value: &str) -> Result<Self, Self::Err> {
43 let bytes = value.as_bytes();
44 let valid = (1..=MAX_AGENT_ID_BYTES).contains(&bytes.len())
45 && bytes[0].is_ascii_lowercase()
46 && bytes[1..]
47 .iter()
48 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-');
49 if valid {
50 Ok(Self(value.to_owned()))
51 } else {
52 Err(format!(
53 "Invalid ACP agent id {value:?}: expected 1–{MAX_AGENT_ID_BYTES} lowercase ASCII letters, digits or hyphens starting with a letter."
54 ))
55 }
56 }
57}
58
59impl<'de> Deserialize<'de> for AgentId {
60 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
61 String::deserialize(deserializer)?
62 .parse()
63 .map_err(serde::de::Error::custom)
64 }
65}
66
67impl fmt::Display for AgentId {
68 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69 formatter.write_str(&self.0)
70 }
71}
72
73impl AsRef<str> for AgentId {
74 fn as_ref(&self) -> &str {
75 &self.0
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum ConfigCategory {
83 Model,
84 Mode,
85 ThoughtLevel,
86 Other,
87}
88
89impl ConfigCategory {
90 pub(crate) fn apply_rank(self) -> u8 {
93 match self {
94 Self::Model => 0,
95 Self::Mode => 1,
96 Self::ThoughtLevel => 2,
97 Self::Other => 3,
98 }
99 }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct ConfigChoice {
106 pub value: String,
107 pub name: String,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub description: Option<String>,
110 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
112 pub bypass_warning: bool,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct ConfigOption {
119 pub id: String,
120 pub name: String,
121 pub category: ConfigCategory,
122 pub current_value: String,
123 pub choices: Vec<ConfigChoice>,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(rename_all = "camelCase")]
129pub struct ConfigSelection {
130 pub id: String,
131 pub value: String,
132 #[serde(default)]
133 pub category: Option<ConfigCategory>,
134}
135
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139pub enum VerifyBridgeState {
140 #[default]
141 NotConnected,
142 Connected,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct ToolLocation {
149 pub path: String,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub line: Option<u32>,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(rename_all = "camelCase")]
157pub struct ToolDiff {
158 pub path: String,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub old_text: Option<String>,
161 pub new_text: String,
162 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
163 pub truncated: bool,
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169pub enum ToolStatus {
170 Pending,
171 Running,
172 Completed,
173 Failed,
174 Cancelled,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub enum PlanStepStatus {
181 Pending,
182 InProgress,
183 Completed,
184 Failed,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "camelCase")]
190pub struct PlanStep {
191 pub content: String,
192 pub status: PlanStepStatus,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub priority: Option<String>,
195}
196
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(rename_all = "snake_case")]
200pub enum PermissionOptionKind {
201 AllowOnce,
202 AllowAlways,
203 RejectOnce,
204 RejectAlways,
205}
206
207impl PermissionOptionKind {
208 pub fn may_persist_in_agent_settings(self) -> bool {
209 matches!(self, Self::AllowAlways | Self::RejectAlways)
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "camelCase")]
216pub struct PermissionOption {
217 pub option_id: String,
218 pub name: String,
219 pub kind: PermissionOptionKind,
220 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
222 pub persists_in_agent_settings: bool,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
228pub enum PermissionStatus {
229 Pending,
230 Selected,
231 Delivering,
232 Delivered,
233 Cancelled,
234 Expired,
235}
236
237impl PermissionStatus {
238 pub fn as_str(self) -> &'static str {
239 match self {
240 Self::Pending => "PENDING",
241 Self::Selected => "SELECTED",
242 Self::Delivering => "DELIVERING",
243 Self::Delivered => "DELIVERED",
244 Self::Cancelled => "CANCELLED",
245 Self::Expired => "EXPIRED",
246 }
247 }
248
249 pub fn from_db(value: &str) -> Result<Self, String> {
250 match value {
251 "PENDING" => Ok(Self::Pending),
252 "SELECTED" => Ok(Self::Selected),
253 "DELIVERING" => Ok(Self::Delivering),
254 "DELIVERED" => Ok(Self::Delivered),
255 "CANCELLED" => Ok(Self::Cancelled),
256 "EXPIRED" => Ok(Self::Expired),
257 other => Err(format!("Unknown chat permission status {other:?}.")),
258 }
259 }
260}
261
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265pub struct PermissionRecord {
266 pub session_id: crate::types::SessionId,
267 pub owner_token: String,
268 pub permission_id: String,
269 pub rpc_request_id: String,
270 pub title: String,
271 pub tool_kind: crate::chat::ToolKind,
272 pub summary: String,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub detail: Option<String>,
275 pub options: Vec<PermissionOption>,
276 pub status: PermissionStatus,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub selected_option_id: Option<String>,
279 pub created_at: crate::types::Timestamp,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub resolved_at: Option<crate::types::Timestamp>,
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
286#[serde(rename_all = "camelCase")]
287pub struct WarmOwner {
288 pub pid: u32,
289 pub start_time: u64,
290}
291
292impl WarmOwner {
293 pub(crate) fn current() -> Result<Self, String> {
294 let identity = crate::process::child_identity(std::process::id())
295 .map_err(|error| error.to_string())?;
296 Ok(Self {
297 pid: identity.pid.get(),
298 start_time: identity.start_time,
299 })
300 }
301}
302
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase")]
307pub struct AcpBinding {
308 pub agent_id: AgentId,
309 #[serde(with = "crate::platform::path_serde")]
310 pub worktree: PathBuf,
311 pub checkout: repository::Identity,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub remote_session_id: Option<String>,
314 pub generation: u64,
315 #[serde(default)]
317 pub settled_send: usize,
318 #[serde(default)]
320 pub runtime_fingerprint: String,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub warm_owner: Option<WarmOwner>,
323}
324
325#[derive(Debug, Clone, PartialEq, Eq)]
327pub enum Problem {
328 Missing {
329 agent: String,
330 hint: String,
331 },
332 TooOld {
333 agent: String,
334 version: semver::Version,
335 minimum: semver::Version,
336 },
337 SignedOut {
338 agent: String,
339 hint: String,
340 },
341 Quota {
342 agent: String,
343 },
344 RateLimit {
345 agent: String,
346 },
347 TrustRequired(Box<trust::TrustRequirement>),
348 ModeMismatch {
349 requested: String,
350 actual: Option<String>,
351 },
352 Failed(String),
353}
354
355impl Problem {
356 pub(crate) fn classify_text(agent: &str, hint: &str, text: &str) -> Option<Self> {
357 let lower = text.to_ascii_lowercase();
358 let contains = |markers: &[&str]| markers.iter().any(|marker| lower.contains(marker));
359 if contains(&[
360 "authentication required",
361 "auth_required",
362 "unauthenticated",
363 "not authenticated",
364 "not logged in",
365 "not signed in",
366 "login required",
367 "select an authentication method",
368 "no auth method",
369 "credentials not found",
370 "no browser is available here",
371 ]) {
372 Some(Self::SignedOut {
373 agent: agent.to_owned(),
374 hint: hint.to_owned(),
375 })
376 } else if contains(&[
377 "quota_exhausted",
378 "quota exhausted",
379 "quota exceeded",
380 "usage limit reached",
381 "usage quota",
382 ]) {
383 Some(Self::Quota {
384 agent: agent.to_owned(),
385 })
386 } else if contains(&[
387 "resource_exhausted",
388 "rate_limit_exceeded",
389 "rate limit",
390 "error 429",
391 "code 429",
392 ]) || lower.starts_with("429 ")
393 {
394 Some(Self::RateLimit {
395 agent: agent.to_owned(),
396 })
397 } else {
398 None
399 }
400 }
401}
402
403impl From<Problem> for Failure {
404 fn from(problem: Problem) -> Self {
405 match problem {
406 Problem::Missing { agent, hint } => Self::new(
407 Code::Authentication,
408 format!("{agent} is not installed on PATH. {hint}"),
409 ),
410 Problem::TooOld {
411 agent,
412 version,
413 minimum,
414 } => Self::new(
415 Code::AgentError,
416 format!("{agent} {version} is too old; update to {minimum} or newer."),
417 ),
418 Problem::SignedOut { agent, hint } => Self::new(
419 Code::Authentication,
420 format!("{agent} requires sign-in. {hint}"),
421 ),
422 Problem::Quota { agent } => Self::new(
423 Code::Quota,
424 format!(
425 "Your {agent} account reached its usage quota. Try again when your quota resets."
426 ),
427 ),
428 Problem::RateLimit { agent } => Self::new(
429 Code::RateLimit,
430 format!("{agent} is rate limiting this account. Try again later."),
431 ),
432 Problem::TrustRequired(req) => Self::new(
433 Code::AgentError,
434 format!(
435 "Workspace trust is required before starting {} in {}.",
436 req.agent_id,
437 req.scope.display_label()
438 ),
439 ),
440 Problem::ModeMismatch { requested, actual } => Self::new(
441 Code::AgentError,
442 match actual {
443 Some(actual) => format!(
444 "ACP agent did not confirm requested mode {requested:?} (reported {actual:?}); refusing silent approval-mode downgrade."
445 ),
446 None => format!(
447 "Requested mode {requested:?} is no longer offered by the ACP agent; refusing silent approval-mode downgrade."
448 ),
449 },
450 ),
451 Problem::Failed(message) => Self::new(Code::ProviderError, message),
452 }
453 }
454}