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