anyagent 0.0.3

One Rust interface to the coding agents installed on a machine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Public types for discovery, sessions, configuration, and input.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::time::Duration;

use serde::{Deserialize, Serialize};

macro_rules! string_id {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            /// Wraps a string as this id.
            pub fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }
            /// The id as text.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl<T: Into<String>> From<T> for $name {
            fn from(value: T) -> Self {
                Self(value.into())
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(&self.0)
            }
        }
    };
}
pub(crate) use string_id;

string_id!(AgentId); // Agent catalog id, such as "claude" or "codex".
string_id!(ConfigId); // Session option id, such as "model" or "effort".
string_id!(ResumeToken); // Opaque token owned by the agent.

/// Where discovery found an executable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum InstallationSource {
    EnvOverride,
    Path,
    LoginShellPath,
    VersionManager,
    KnownLocation,
    Pinned,
}

/// One installed agent, as returned by `Runtime::discover`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AgentInstallation {
    pub id: AgentId,
    pub name: String,
    pub executable_path: PathBuf,
    pub source: InstallationSource,
    /// A richer runtime for this agent that is not installed (Antigravity's
    /// ACP server). `open` works without it with fewer capabilities; the
    /// record says what to install to get the rest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upgrade: Option<crate::runtime::MissingAgent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) acp_args: Option<Vec<String>>,
}

impl AgentInstallation {
    /// Uses an exact executable for a catalog agent.
    pub fn at(id: impl Into<AgentId>, executable: impl Into<PathBuf>) -> Self {
        let id = id.into();
        Self {
            name: id.to_string(),
            id,
            executable_path: executable.into(),
            source: InstallationSource::Pinned,
            upgrade: None,
            acp_args: None,
        }
    }

    /// Launches an ACP agent that is not yet in the catalog.
    pub fn acp(name: impl Into<String>, executable: impl Into<PathBuf>, args: Vec<String>) -> Self {
        let name = name.into();
        Self {
            id: AgentId::new(&name),
            name,
            executable_path: executable.into(),
            source: InstallationSource::Pinned,
            upgrade: None,
            acp_args: Some(args),
        }
    }
}

/// Whether, and how, an agent is logged in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum AuthStatus {
    Authenticated {
        kind: AuthKind,
        account: Option<AccountInfo>,
    },
    Unauthenticated {
        login: Vec<LoginMethod>,
    },
    Unknown,
}

/// The login kind decides which features exist (plan usage needs a subscription).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum AuthKind {
    Subscription,
    ApiKey,
    CloudProvider,
    Other(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AccountInfo {
    pub email: Option<String>,
    pub plan: Option<String>,
}

/// A login method the application can show to the user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum LoginMethod {
    /// Run this full argv in a terminal the user can see.
    Terminal {
        command: Vec<String>,
        env: BTreeMap<String, String>,
        description: String,
    },
    /// Set this environment variable before `open`.
    EnvVar { name: String },
}

/// Optional actions supported by an agent or session.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum Capability {
    Images,
    Resume,
    Steer,
    Permissions,
    Questions,
    Rollback,
    /// `rollback` may also restore the files the dropped turns changed.
    RollbackFiles,
    Fork,
    /// `compact` can summarize the session's context on demand.
    Compact,
    SlashCommands,
    Plan,
    Subagents,
    ContextUsage,
    PlanUsage,
}

/// What `rollback` rewinds: conversation context only, or also the files
/// the agent changed in the dropped turns (requires `RollbackFiles`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum RollbackScope {
    Conversation,
    ConversationAndFiles,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum McpTransport {
    Stdio,
    Http,
    Sse,
}

/// A client-owned MCP server the agent should connect to, forwarded at open.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct McpServer {
    pub(crate) name: String,
    pub(crate) connection: McpConnection,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub(crate) enum McpConnection {
    Stdio {
        command: PathBuf,
        args: Vec<String>,
        env: BTreeMap<String, String>,
    },
    Http {
        url: String,
        headers: BTreeMap<String, String>,
    },
    Sse {
        url: String,
        headers: BTreeMap<String, String>,
    },
}

impl McpServer {
    /// A server the agent launches itself. `command` should be absolute.
    pub fn stdio(
        name: impl Into<String>,
        command: impl Into<PathBuf>,
        args: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            connection: McpConnection::Stdio {
                command: command.into(),
                args: args.into_iter().map(Into::into).collect(),
                env: BTreeMap::new(),
            },
        }
    }

    /// A server already running over streamable HTTP.
    pub fn http(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            connection: McpConnection::Http {
                url: url.into(),
                headers: BTreeMap::new(),
            },
        }
    }

    /// A server already running over SSE.
    pub fn sse(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            connection: McpConnection::Sse {
                url: url.into(),
                headers: BTreeMap::new(),
            },
        }
    }

    /// Connection metadata: an env var for stdio, an HTTP header otherwise.
    pub fn with(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        match &mut self.connection {
            McpConnection::Stdio { env, .. } => env.insert(key.into(), value.into()),
            McpConnection::Http { headers, .. } | McpConnection::Sse { headers, .. } => {
                headers.insert(key.into(), value.into())
            }
        };
        self
    }

    /// Which transport this server's connection uses.
    pub(crate) fn transport(&self) -> McpTransport {
        match self.connection {
            McpConnection::Stdio { .. } => McpTransport::Stdio,
            McpConnection::Http { .. } => McpTransport::Http,
            McpConnection::Sse { .. } => McpTransport::Sse,
        }
    }
}

/// Effective caller actions for one agent or session.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Capabilities {
    features: BTreeSet<Capability>,
    pub mcp_transports: Vec<McpTransport>,
}

impl Capabilities {
    /// A set of features with no MCP transports.
    pub fn new(features: impl IntoIterator<Item = Capability>) -> Self {
        Self {
            features: features.into_iter().collect(),
            mcp_transports: Vec::new(),
        }
    }

    /// Whether the agent or session offers this action.
    pub fn supports(&self, cap: Capability) -> bool {
        self.features.contains(&cap)
    }

    /// Every supported action, for listing.
    pub fn iter(&self) -> impl Iterator<Item = &Capability> {
        self.features.iter()
    }

    /// Adds an action an adapter discovered after the handshake.
    pub(crate) fn add(&mut self, cap: Capability) {
        self.features.insert(cap);
    }
}

/// A session setting the agent advertises. Well-known ids: `model`, `effort`,
/// `mode`, `sandbox`, `fast` (boolean, lower latency with increased usage).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConfigOption {
    pub id: ConfigId,
    pub name: String,
    pub category: Option<String>,
    pub kind: ConfigKind,
    pub current: Option<ConfigValue>,
    /// Changeable through `Session::configure`; the adapter may resume internally.
    pub live: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum ConfigKind {
    Select { choices: Vec<ConfigChoice> },
    Boolean,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ConfigChoice {
    pub value: String,
    pub label: String,
    pub description: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum ConfigValue {
    Text(String),
    Bool(bool),
}

impl From<&str> for ConfigValue {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

impl From<String> for ConfigValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<bool> for ConfigValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SlashCommand {
    pub name: String,
    pub description: String,
    pub input_hint: Option<String>,
}

/// What `probe` and `open` learn about an agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AgentDetails {
    pub version: Option<String>,
    pub auth: AuthStatus,
    pub capabilities: Capabilities,
    pub config_options: Vec<ConfigOption>,
    pub commands: Vec<SlashCommand>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SessionConfiguration {
    pub options: BTreeMap<ConfigId, ConfigValue>,
}

/// How anyagent handles tool permission requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum PermissionMode {
    /// Forward each request to the application.
    Ask,
    /// Allow each permission request once without forwarding it.
    AutoApprove,
}

/// Creation-time settings for `Runtime::open`.
#[derive(Debug, Clone)]
pub struct SessionOptions {
    pub(crate) cwd: PathBuf,
    pub(crate) start: SessionStart,
    pub(crate) permission_mode: PermissionMode,
    pub(crate) no_tools: bool,
    /// Never persisted: keeps probes and one-shot generation out of the
    /// user's session history.
    pub(crate) throwaway: bool,
    pub(crate) quiet_window: Option<Duration>,
    pub(crate) stall_after: Option<Duration>,
    pub(crate) mcp_servers: Vec<McpServer>,
    pub(crate) configure: Vec<(ConfigId, ConfigValue)>,
    pub(crate) config_home: Option<PathBuf>,
    pub(crate) record_wire: Option<PathBuf>,
}

/// How `open` binds to a provider session.
#[derive(Debug, Clone)]
pub(crate) enum SessionStart {
    New,
    Resume(ResumeToken),
    Fork {
        from: ResumeToken,
        at: Option<crate::event::MessageId>,
    },
}
impl SessionOptions {
    /// Working directory the agent runs in. Required. A relative path is made
    /// absolute (lexically, no disk access): some agents reject a relative cwd.
    pub fn in_dir(cwd: impl Into<PathBuf>) -> Self {
        let cwd = cwd.into();
        Self {
            cwd: std::path::absolute(&cwd).unwrap_or(cwd),
            start: SessionStart::New,
            permission_mode: PermissionMode::Ask,
            no_tools: false,
            throwaway: false,
            quiet_window: None,
            stall_after: None,
            mcp_servers: Vec::new(),
            configure: Vec::new(),
            config_home: None,
            record_wire: None,
        }
    }

    /// Set an advertised config option at creation — the path for options
    /// with `live: false` (e.g. a non-live `model`). `open` fails with
    /// `InvalidConfiguration` when the agent refuses the value.
    pub fn configure(mut self, id: impl Into<ConfigId>, value: impl Into<ConfigValue>) -> Self {
        self.configure.push((id.into(), value.into()));
        self
    }

    /// Resume a provider session instead of creating a new one.
    pub fn resume(mut self, token: ResumeToken) -> Self {
        self.start = SessionStart::Resume(token);
        self
    }

    /// Branch a provider session into a new one that starts with its
    /// conversation; the original stays untouched. `None` forks at the tip.
    /// `at` cuts the copied history after that message, in the id currency
    /// the adapter documents (claude: the `claude/fork_point` extension on
    /// `MessageEnded`). Requires `Capability::Fork`; `open` fails typed
    /// without it.
    pub fn fork_from(mut self, token: ResumeToken, at: Option<crate::event::MessageId>) -> Self {
        self.start = SessionStart::Fork { from: token, at };
        self
    }

    /// Forward a client-owned MCP server. `open` fails with
    /// `UnsupportedFeature` when the agent lacks the server's transport.
    pub fn mcp_server(mut self, server: McpServer) -> Self {
        self.mcp_servers.push(server);
        self
    }

    /// How tool permission requests are handled; `Ask` by default.
    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
        self.permission_mode = mode;
        self
    }

    /// Point the agent at a separate config directory so one machine can hold
    /// several logins side by side (claude: `CLAUDE_CONFIG_DIR`, codex:
    /// `CODEX_HOME`). This is the supported way to keep logins apart;
    /// credential copying stays the application's job. `open` fails with
    /// `InvalidConfiguration` on an agent that has no known config-home
    /// variable, rather than silently ignoring the request.
    pub fn config_home(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config_home = Some(dir.into());
        self
    }

    /// Tee every raw protocol frame, both directions, to `path` for bug
    /// reports: one JSON object per line, `{"dir":"in"|"out","frame":<frame>}`,
    /// append-only and flushed per line. A recording failure never fails a
    /// turn. Unset (the default) records nothing.
    ///
    /// The file is unredacted — prompts, file contents, command output, and
    /// possibly secrets — so treat it as sensitive and delete it after use.
    pub fn record_wire(mut self, path: impl Into<PathBuf>) -> Self {
        self.record_wire = Some(path.into());
        self
    }

    /// Overrides the quiet window used to infer turn end on agents whose
    /// wire does not end turns deterministically. Diagnostics only.
    pub fn quiet_window(mut self, window: Duration) -> Self {
        self.quiet_window = Some(window);
        self
    }

    /// How long the agent may stay silent mid-turn before a stall warning
    /// `Diagnostic` (default 120 s). It warns once per silence; never ends
    /// the turn.
    pub fn stall_after(mut self, after: Duration) -> Self {
        self.stall_after = Some(after);
        self
    }

    /// The working directory the agent runs in.
    pub fn cwd(&self) -> &PathBuf {
        &self.cwd
    }
}

/// One prompt: text plus optional attachments.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Input {
    pub(crate) text: String,
    pub(crate) attachments: Vec<PathBuf>,
}

impl Input {
    /// A text-only prompt.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            attachments: Vec::new(),
        }
    }

    /// Attach a file by path. Every attachment is referenced by path in the
    /// prompt text so the agent can open it; images under the inline cap are
    /// additionally sent as image blocks when the wire supports them.
    pub fn attach(mut self, path: impl Into<PathBuf>) -> Self {
        self.attachments.push(path.into());
        self
    }

    /// The prompt text without attachments.
    pub fn as_text(&self) -> &str {
        &self.text
    }
}

impl From<&str> for Input {
    fn from(text: &str) -> Self {
        Self::text(text)
    }
}

impl From<String> for Input {
    fn from(text: String) -> Self {
        Self::text(text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// SessionOptions::in_dir absolutizes relative cwd so agents rejecting relative paths work.
    #[test]
    fn in_dir_makes_cwd_absolute() {
        // Agents such as grok reject a relative cwd at `session/new`.
        assert_eq!(
            SessionOptions::in_dir(".").cwd(),
            &std::env::current_dir().unwrap()
        );
        let abs = std::env::temp_dir();
        assert_eq!(SessionOptions::in_dir(&abs).cwd(), &abs);
    }
}