Skip to main content

objectiveai_cli/
error.rs

1#[derive(Debug, thiserror::Error)]
2pub enum Error {
3    #[error("{0}")]
4    Filesystem(#[from] crate::filesystem::Error),
5    #[error("{}", format_http_error(.0))]
6    Http(#[from] objectiveai_sdk::HttpError),
7    #[error("{0}")]
8    ResponseError(objectiveai_sdk::error::ResponseError),
9    #[error("{0} source is not supported for function-profile pairs")]
10    PairsSourceNotSupported(&'static str),
11    #[error("authorization is global only")]
12    AuthorizationGlobalOnly,
13    #[error("{0}")]
14    MissingArgs(&'static str),
15    #[error("invalid path: {0}")]
16    PathParse(String),
17    #[error("python wasm runtime error: {0}")]
18    PythonWasm(String),
19    #[error("failed to read python file {0}: {1}")]
20    PythonFileRead(std::path::PathBuf, std::io::Error),
21    #[error("failed to read prompt file {0}: {1}")]
22    PromptFileRead(std::path::PathBuf, std::io::Error),
23    #[error("failed to read JSON file {0}: {1}")]
24    JsonFileRead(std::path::PathBuf, std::io::Error),
25    #[error("python exception:\n{0}")]
26    PythonException(String),
27    #[error("python script produced no output")]
28    PythonNoOutput,
29    #[error("python output deserialization failed: {0}")]
30    PythonDeserialize(serde_path_to_error::Error<serde_json::Error>),
31    #[error("internal error: python harness output is malformed: {0}")]
32    PythonHarnessBroken(String),
33    #[error("inline JSON deserialization failed: {0}")]
34    InlineDeserialize(serde_path_to_error::Error<serde_json::Error>),
35    #[error("inline JSON conversion failed: {0}")]
36    InlineJson(#[from] serde_json::Error),
37    #[error("stream ended without producing any chunks")]
38    EmptyStream,
39    #[error("config set forbidden by server configuration")]
40    ConfigSetForbidden,
41    #[error("log writer task panicked or was cancelled")]
42    WriterPanic,
43    #[error("subscribe timed out")]
44    LogSubscribeTimedOut,
45    #[error("plugin not found: {0}")]
46    PluginNotFound(String),
47    #[error("failed to spawn plugin: {0}")]
48    PluginSpawn(std::io::Error),
49    #[error("failed to read plugin output: {0}")]
50    PluginRead(std::io::Error),
51    #[error("plugin exited with non-zero status: {0}")]
52    PluginExit(i32),
53    #[error("plugins may not invoke `{0}` commands")]
54    PluginCommandForbidden(&'static str),
55    #[error("tool not found: {0}")]
56    ToolNotFound(String),
57    #[error("failed to spawn tool: {0}")]
58    ToolSpawn(std::io::Error),
59    #[error("failed to read tool output: {0}")]
60    ToolRead(std::io::Error),
61    #[error("tool exited with non-zero status: {0}")]
62    ToolExit(i32),
63    #[error(
64        "{kind} {owner}/{repository} (commit {commit_sha}, version {version}) is not in the install whitelist; pass --allow-untrusted to install anyway"
65    )]
66    NotWhitelisted {
67        kind: &'static str,
68        owner: String,
69        repository: String,
70        commit_sha: String,
71        version: String,
72    },
73    #[error("whitelist regex error: {0}")]
74    WhitelistRegex(regex::Error),
75    #[error("viewer path must start with `/`, got {0:?}")]
76    ViewerPathMissingSlash(String),
77    #[error("viewer http error: {0}")]
78    ViewerSendHttp(String),
79    #[error("updater: {0}")]
80    Updater(String),
81    #[error("instance runner: {0}")]
82    Instance(String),
83    #[error("not found: {0}")]
84    NotFound(String),
85    #[error("{0} remote is not supported for this command")]
86    RemoteNotSupported(&'static str),
87    #[error("{0}")]
88    ClapParse(#[from] clap::Error),
89    #[error("argument parse error at `{}`: {}", .0.field, .0.source)]
90    FromArgs(#[from] objectiveai_sdk::cli::command::FromArgsError),
91    #[error("{name} exited before publishing its lock ({status}); stdout: {stdout}; stderr: {stderr}")]
92    SpawnExitedBeforePublishing {
93        name: String,
94        status: std::process::ExitStatus,
95        stdout: String,
96        stderr: String,
97    },
98    #[error("lockfile {key}: {source}")]
99    Lockfile { key: String, source: std::io::Error },
100    #[error("spawn {0}: {1}")]
101    Spawn(String, std::io::Error),
102    #[error(
103        "no prior agent_completion_request for agent {agent_instance_hierarchy:?}; spawn the agent first with `agents spawn`"
104    )]
105    AgentNoPriorRequest { agent_instance_hierarchy: String },
106    #[error(
107        "agent {agent_instance_hierarchy:?} has no continuations available across {request_count} prior request(s); the most recent turn may still be streaming, or none have finished. Cannot fall back without a continuation."
108    )]
109    AgentNoContinuation {
110        agent_instance_hierarchy: String,
111        request_count: usize,
112    },
113    #[error(
114        "tag {tag:?} exists but the agent has not been spawned yet (tag_group_id={tag_group_id}, parent_agent_instance_hierarchy={parent_agent_instance_hierarchy:?})"
115    )]
116    TagGrouped {
117        tag: String,
118        tag_group_id: i64,
119        parent_agent_instance_hierarchy: String,
120    },
121    #[error("tag {0:?} is not registered")]
122    TagNotFound(String),
123    #[error(
124        "agent instance {agent_instance_hierarchy:?} is already active (its lock is held by a live process)"
125    )]
126    AgentInstanceActive { agent_instance_hierarchy: String },
127    #[error("agent tag {tag:?} is already being spawned (its lock is held by a live process)")]
128    AgentTagActive { tag: String },
129    #[error("cannot enqueue against an agent ref; enqueue targets an instance or a tag")]
130    EnqueueRefTarget,
131    #[error("cannot wait on an agent ref; wait targets an instance or a tag")]
132    WaitRefTarget,
133    #[error(
134        "FATAL: tag {tag:?} lock was released without its GROUPED->BOUND upgrade; the spawn flow's upgrade-before-release invariant is broken"
135    )]
136    TagLockDroppedWithoutUpgrade { tag: String },
137    #[error(
138        "queued message {id} was sent by {sender_agent_instance_hierarchy:?}; it can only be deleted by the sender or a parent of the sender (caller is {caller_agent_instance_hierarchy:?})"
139    )]
140    QueueDeleteUnauthorized {
141        id: i64,
142        sender_agent_instance_hierarchy: String,
143        caller_agent_instance_hierarchy: String,
144    },
145    #[error(
146        "a schedule named {name:?} already exists for {agent_instance_hierarchy:?}; pass --overwrite to replace it"
147    )]
148    ScheduleAlreadyExists {
149        name: String,
150        agent_instance_hierarchy: String,
151    },
152    #[error("db: {0}")]
153    Db(#[from] crate::db::Error),
154    /// Endpoint exists in the command tree but the underlying
155    /// implementation hasn't landed yet — typically because it depends
156    /// on the postgres-backed `logs.*` reader that's still in flight.
157    #[error("not implemented: {0}")]
158    NotImplemented(&'static str),
159    #[error("invalid query: {0}")]
160    InvalidQuery(String),
161    #[error("query exceeded timeout")]
162    QueryTimeout,
163    #[error("query attempted a write in a read-only context")]
164    QueryReadOnlyViolation,
165    /// The executor's whole-stream deadline elapsed. Yielded as the
166    /// stream's final item; the stream never outlives the timeout.
167    #[error("timed out after {timeout_seconds}s")]
168    Timeout { timeout_seconds: u64 },
169    /// The executor's running token tally over the serialized output
170    /// exceeded the request's `max_tokens` budget. Yielded as the
171    /// stream's final item in place of the item that pushed it over.
172    #[error("response exceeded token budget — actual {actual} tokens, limit {limit}")]
173    TokenBudgetExceeded { limit: u64, actual: u64 },
174}
175
176impl Error {
177    /// JSON value to use when serializing this error in user-facing
178    /// output. For `ResponseError` this is the inner error serialized
179    /// as a structured object; for everything else it's a string built
180    /// from the `Display` impl.
181    pub fn output_message(&self) -> serde_json::Value {
182        match self {
183            Error::ResponseError(re) => {
184                serde_json::to_value(re).unwrap_or_else(|_| self.to_string().into())
185            }
186            _ => self.to_string().into(),
187        }
188    }
189}
190
191fn http_is_connect_failure(err: &objectiveai_sdk::HttpError) -> bool {
192    use objectiveai_sdk::HttpError as H;
193    let reqwest_err = match err {
194        H::StreamError(reqwest_eventsource::Error::Transport(e)) => e,
195        H::RequestError(e) | H::HttpError(e) => e,
196        _ => return false,
197    };
198    reqwest_err.is_connect() || reqwest_err.is_timeout()
199}
200
201fn format_http_error(err: &objectiveai_sdk::HttpError) -> String {
202    if http_is_connect_failure(err) {
203        format!(
204            "{err}\n\nhint: this looks like a connection failure to the resolved API \
205address. the cli auto-spawns a local objectiveai-api when no address is \
206configured; if you set `api.address`, verify it \
207(`objectiveai api config address get --final`) or unset it to use the \
208local server. to (re)start the local server: `objectiveai api spawn`"
209        )
210    } else {
211        err.to_string()
212    }
213}