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        "plugin {owner}/{repository} (commit {commit_sha}, version {version}) is not in the install whitelist; pass --allow-untrusted to install anyway"
65    )]
66    PluginNotWhitelisted {
67        owner: String,
68        repository: String,
69        commit_sha: String,
70        version: String,
71    },
72    #[error("whitelist regex error: {0}")]
73    WhitelistRegex(regex::Error),
74    #[error("viewer path must start with `/`, got {0:?}")]
75    ViewerPathMissingSlash(String),
76    #[error("viewer http error: {0}")]
77    ViewerSendHttp(String),
78    #[error("updater: {0}")]
79    Updater(String),
80    #[error("instance runner: {0}")]
81    Instance(String),
82    #[error("not found: {0}")]
83    NotFound(String),
84    #[error("{0} remote is not supported for this command")]
85    RemoteNotSupported(&'static str),
86    #[error("{0}")]
87    ClapParse(#[from] clap::Error),
88    #[error("argument parse error at `{}`: {}", .0.field, .0.source)]
89    FromArgs(#[from] objectiveai_sdk::cli::command::FromArgsError),
90    #[error("{name} exited before publishing its lock ({status}); stdout: {stdout}; stderr: {stderr}")]
91    SpawnExitedBeforePublishing {
92        name: String,
93        status: std::process::ExitStatus,
94        stdout: String,
95        stderr: String,
96    },
97    #[error("lockfile {key}: {source}")]
98    Lockfile { key: String, source: std::io::Error },
99    #[error("spawn {0}: {1}")]
100    Spawn(String, std::io::Error),
101    #[error(
102        "no prior agent_completion_request for agent {agent_instance_hierarchy:?}; spawn the agent first with `agents spawn`"
103    )]
104    AgentNoPriorRequest { agent_instance_hierarchy: String },
105    #[error(
106        "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."
107    )]
108    AgentNoContinuation {
109        agent_instance_hierarchy: String,
110        request_count: usize,
111    },
112    #[error(
113        "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:?})"
114    )]
115    TagGrouped {
116        tag: String,
117        tag_group_id: i64,
118        parent_agent_instance_hierarchy: String,
119    },
120    #[error("tag {0:?} is not registered")]
121    TagNotFound(String),
122    #[error(
123        "agent instance {agent_instance_hierarchy:?} is already active (its lock is held by a live process)"
124    )]
125    AgentInstanceActive { agent_instance_hierarchy: String },
126    #[error("agent tag {tag:?} is already being spawned (its lock is held by a live process)")]
127    AgentTagActive { tag: String },
128    #[error("cannot enqueue against an agent ref; enqueue targets an instance or a tag")]
129    EnqueueRefTarget,
130    #[error("cannot wait on an agent ref; wait targets an instance or a tag")]
131    WaitRefTarget,
132    #[error(
133        "FATAL: tag {tag:?} lock was released without its GROUPED->BOUND upgrade; the spawn flow's upgrade-before-release invariant is broken"
134    )]
135    TagLockDroppedWithoutUpgrade { tag: String },
136    #[error(
137        "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:?})"
138    )]
139    QueueDeleteUnauthorized {
140        id: i64,
141        sender_agent_instance_hierarchy: String,
142        caller_agent_instance_hierarchy: String,
143    },
144    #[error(
145        "a schedule named {name:?} already exists for {agent_instance_hierarchy:?}; pass --overwrite to replace it"
146    )]
147    ScheduleAlreadyExists {
148        name: String,
149        agent_instance_hierarchy: String,
150    },
151    #[error("db: {0}")]
152    Db(#[from] crate::db::Error),
153    /// Endpoint exists in the command tree but the underlying
154    /// implementation hasn't landed yet — typically because it depends
155    /// on the postgres-backed `logs.*` reader that's still in flight.
156    #[error("not implemented: {0}")]
157    NotImplemented(&'static str),
158    #[error("invalid query: {0}")]
159    InvalidQuery(String),
160    #[error("query exceeded timeout")]
161    QueryTimeout,
162    #[error("query attempted a write in a read-only context")]
163    QueryReadOnlyViolation,
164    /// The executor's whole-stream deadline elapsed. Yielded as the
165    /// stream's final item; the stream never outlives the timeout.
166    #[error("timed out after {timeout_seconds}s")]
167    Timeout { timeout_seconds: u64 },
168    /// The executor's running token tally over the serialized output
169    /// exceeded the request's `max_tokens` budget. Yielded as the
170    /// stream's final item in place of the item that pushed it over.
171    #[error("response exceeded token budget — actual {actual} tokens, limit {limit}")]
172    TokenBudgetExceeded { limit: u64, actual: u64 },
173}
174
175impl Error {
176    /// JSON value to use when serializing this error in user-facing
177    /// output. For `ResponseError` this is the inner error serialized
178    /// as a structured object; for everything else it's a string built
179    /// from the `Display` impl.
180    pub fn output_message(&self) -> serde_json::Value {
181        match self {
182            Error::ResponseError(re) => {
183                serde_json::to_value(re).unwrap_or_else(|_| self.to_string().into())
184            }
185            _ => self.to_string().into(),
186        }
187    }
188}
189
190fn http_is_connect_failure(err: &objectiveai_sdk::HttpError) -> bool {
191    use objectiveai_sdk::HttpError as H;
192    let reqwest_err = match err {
193        H::StreamError(reqwest_eventsource::Error::Transport(e)) => e,
194        H::RequestError(e) | H::HttpError(e) => e,
195        _ => return false,
196    };
197    reqwest_err.is_connect() || reqwest_err.is_timeout()
198}
199
200fn format_http_error(err: &objectiveai_sdk::HttpError) -> String {
201    if http_is_connect_failure(err) {
202        format!(
203            "{err}\n\nhint: this looks like a connection failure to the resolved API \
204address. the cli auto-spawns a local objectiveai-api when no address is \
205configured; if you set `api.address`, verify it \
206(`objectiveai api config address get --final`) or unset it to use the \
207local server. to (re)start the local server: `objectiveai api spawn`"
208        )
209    } else {
210        err.to_string()
211    }
212}