Skip to content

Commit c1ebee6

Browse files
feat: support for provider selection (tailcallhq#1603)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 5dd93af commit c1ebee6

35 files changed

Lines changed: 1157 additions & 701 deletions

‎AGENTS.md‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,170 @@ Always verify changes by running tests and linting the codebase
102102
- Safely assume git is pre-installed
103103
- Safely assume github cli (gh) is pre-installed
104104
- Always use `Co-Authored-By: ForgeCode <noreply@forgecode.dev>` for git commits and Github comments
105+
106+
## Service Implementation Guidelines
107+
108+
Services should follow clean architecture principles and maintain clear separation of concerns:
109+
110+
### Core Principles
111+
112+
- **No service-to-service dependencies**: Services should never depend on other services directly
113+
- **Infrastructure dependency**: Services should depend only on infrastructure abstractions when needed
114+
- **Single type parameter**: Services should take at most one generic type parameter for infrastructure
115+
- **No trait objects**: Avoid `Box<dyn ...>` - use concrete types and generics instead
116+
- **Constructor pattern**: Implement `new()` without type bounds - apply bounds only on methods that need them
117+
- **Compose dependencies**: Use the `+` operator to combine multiple infrastructure traits into a single bound
118+
- **Arc<T> for infrastructure**: Store infrastructure as `Arc<T>` for cheap cloning and shared ownership
119+
- **Tuple struct pattern**: For simple services with single dependency, use tuple structs `struct Service<T>(Arc<T>)`
120+
121+
### Examples
122+
123+
#### Simple Service (No Infrastructure)
124+
125+
```rust
126+
use anyhow::Result;
127+
128+
pub struct UserValidationService;
129+
130+
impl UserValidationService {
131+
pub fn new() -> Self {
132+
Self
133+
}
134+
135+
pub fn validate_email(&self, email: &str) -> Result<()> {
136+
if !email.contains('@') {
137+
anyhow::bail!("Invalid email format");
138+
}
139+
Ok(())
140+
}
141+
142+
pub fn validate_age(&self, age: u32) -> Result<()> {
143+
if age < 18 {
144+
anyhow::bail!("User must be at least 18 years old");
145+
}
146+
Ok(())
147+
}
148+
}
149+
```
150+
151+
#### Service with Infrastructure Dependency
152+
153+
```rust
154+
// Infrastructure trait (defined in infrastructure layer)
155+
pub trait UserRepository {
156+
fn find_by_email(&self, email: &str) -> Result<Option<User>>;
157+
fn save(&self, user: &User) -> Result<()>;
158+
}
159+
160+
// Service with single generic parameter using Arc
161+
pub struct UserService<R> {
162+
repository: Arc<R>,
163+
}
164+
165+
impl<R> UserService<R> {
166+
// Constructor without type bounds, takes Arc<R>
167+
pub fn new(repository: Arc<R>) -> Self {
168+
Self { repository }
169+
}
170+
}
171+
172+
impl<R: UserRepository> UserService<R> {
173+
// Business logic methods have type bounds where needed
174+
pub fn create_user(&self, email: &str, name: &str) -> Result<User> {
175+
// ...
176+
}
177+
178+
pub fn find_user(&self, email: &str) -> Result<Option<User>> {
179+
// ...
180+
}
181+
}
182+
```
183+
184+
#### Tuple Struct Pattern for Simple Services
185+
186+
```rust
187+
// Infrastructure traits
188+
pub trait FileReader {
189+
async fn read_file(&self, path: &Path) -> Result<String>;
190+
}
191+
192+
pub trait Environment {
193+
fn max_file_size(&self) -> u64;
194+
}
195+
196+
// Tuple struct for simple single dependency service
197+
pub struct FileService<F>(Arc<F>);
198+
199+
impl<F> FileService<F> {
200+
// Constructor without bounds
201+
pub fn new(infra: Arc<F>) -> Self {
202+
Self(infra)
203+
}
204+
}
205+
206+
impl<F: FileReader + Environment> FileService<F> {
207+
// Business logic methods with composed trait bounds
208+
pub async fn read_with_validation(&self, path: &Path) -> Result<String> {
209+
// ...
210+
}
211+
}
212+
```
213+
214+
### Anti-patterns to Avoid
215+
216+
```rust
217+
// BAD: Service depending on another service
218+
pub struct BadUserService<R, E> {
219+
repository: R,
220+
email_service: E, // Don't do this!
221+
}
222+
223+
// BAD: Using trait objects
224+
pub struct BadUserService {
225+
repository: Box<dyn UserRepository>, // Avoid Box<dyn>
226+
}
227+
228+
// BAD: Multiple infrastructure dependencies with separate type parameters
229+
pub struct BadUserService<R, C, L> {
230+
repository: R,
231+
cache: C,
232+
logger: L, // Too many generic parameters - hard to use and test
233+
}
234+
235+
impl<R: UserRepository, C: Cache, L: Logger> BadUserService<R, C, L> {
236+
// BAD: Constructor with type bounds makes it hard to use
237+
pub fn new(repository: R, cache: C, logger: L) -> Self {
238+
Self { repository, cache, logger }
239+
}
240+
}
241+
242+
// BAD: Usage becomes cumbersome
243+
let service = BadUserService::<PostgresRepo, RedisCache, FileLogger>::new(
244+
repo, cache, logger
245+
);
246+
```
247+
248+
### Recommended Patterns
249+
250+
```rust
251+
pub struct UserService<I> {
252+
infra: I,
253+
}
254+
255+
impl<I> UserService<I> {
256+
// GOOD: Constructor without type bounds - cleaner and more flexible
257+
pub fn new(infra: I) -> Self {
258+
Self { infra }
259+
}
260+
}
261+
262+
impl<I: UserRepository + Cache + Logger> UserService<I> {
263+
// Business logic methods have the type bounds where needed
264+
pub fn create_user(&self, email: &str, name: &str) -> Result<User> {
265+
// ...
266+
}
267+
}
268+
269+
// GOOD: Clean usage
270+
let service = UserService::new(combined_infra);
271+
```

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/forge_api/src/api.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::path::{Path, PathBuf};
22

33
use anyhow::Result;
4-
use forge_app::dto::{AppConfig, InitAuth, ToolsOverview};
4+
use forge_app::dto::{InitAuth, ProviderId, ToolsOverview};
55
use forge_app::{User, UserUsage};
66
use forge_domain::AgentId;
77
use forge_stream::MpscStream;
@@ -22,6 +22,8 @@ pub trait API: Sync + Send {
2222
async fn models(&self) -> Result<Vec<Model>>;
2323
/// Provides a list of agents available in the current environment
2424
async fn get_agents(&self) -> Result<Vec<Agent>>;
25+
/// Provides a list of providers available in the current environment
26+
async fn providers(&self) -> Result<Vec<Provider>>;
2527

2628
/// Executes a chat request and returns a stream of responses
2729
async fn chat(&self, chat: ChatRequest) -> Result<MpscStream<Result<ChatResponse>>>;
@@ -97,10 +99,11 @@ pub trait API: Sync + Send {
9799
async fn write_mcp_config(&self, scope: &Scope, config: &McpConfig) -> Result<()>;
98100

99101
async fn init_login(&self) -> Result<InitAuth>;
102+
async fn get_login_info(&self) -> Result<Option<LoginInfo>>;
100103
async fn login(&self, auth: &InitAuth) -> Result<()>;
101104
async fn logout(&self) -> anyhow::Result<()>;
102-
async fn provider(&self) -> anyhow::Result<Provider>;
103-
async fn app_config(&self) -> Option<AppConfig>;
105+
async fn get_provider(&self) -> anyhow::Result<Provider>;
106+
async fn set_provider(&self, provider_id: ProviderId) -> anyhow::Result<()>;
104107
async fn user_info(&self) -> anyhow::Result<Option<User>>;
105108
async fn user_usage(&self) -> anyhow::Result<Option<UserUsage>>;
106109

‎crates/forge_api/src/forge_api.rs‎

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@ use std::path::{Path, PathBuf};
22
use std::sync::Arc;
33

44
use anyhow::{Context, Result};
5-
use forge_app::dto::{AppConfig, InitAuth, ToolsOverview};
5+
use forge_app::dto::{InitAuth, LoginInfo, Provider, ProviderId, ToolsOverview};
66
use forge_app::{
7-
AgentLoaderService, AppConfigService, AuthService, ConversationService, EnvironmentService,
8-
FileDiscoveryService, ForgeApp, McpConfigManager, ProviderRegistry, ProviderService, Services,
9-
User, UserUsage, Walker, WorkflowService,
7+
AgentLoaderService, AuthService, ConversationService, EnvironmentService, FileDiscoveryService,
8+
ForgeApp, McpConfigManager, ProviderRegistry, ProviderService, Services, User, UserUsage,
9+
Walker, WorkflowService,
1010
};
1111
use forge_domain::*;
1212
use forge_infra::ForgeInfra;
13-
use forge_services::{CommandInfra, ForgeServices};
13+
use forge_services::{AppConfigRepository, CommandInfra, ForgeServices};
1414
use forge_stream::MpscStream;
1515

1616
use crate::API;
@@ -35,7 +35,7 @@ impl ForgeAPI<ForgeServices<ForgeInfra>, ForgeInfra> {
3535
}
3636

3737
#[async_trait::async_trait]
38-
impl<A: Services, F: CommandInfra> API for ForgeAPI<A, F> {
38+
impl<A: Services, F: CommandInfra + AppConfigRepository> API for ForgeAPI<A, F> {
3939
async fn discover(&self) -> Result<Vec<File>> {
4040
let environment = self.services.get_environment();
4141
let config = Walker::unlimited().cwd(environment.cwd);
@@ -50,13 +50,17 @@ impl<A: Services, F: CommandInfra> API for ForgeAPI<A, F> {
5050
async fn models(&self) -> Result<Vec<Model>> {
5151
Ok(self
5252
.services
53-
.models(self.provider().await.context("User is not logged in")?)
53+
.models(self.get_provider().await.context("User is not logged in")?)
5454
.await?)
5555
}
5656
async fn get_agents(&self) -> Result<Vec<Agent>> {
5757
Ok(self.services.get_agents().await?)
5858
}
5959

60+
async fn providers(&self) -> Result<Vec<Provider>> {
61+
Ok(self.services.get_all_providers().await?)
62+
}
63+
6064
async fn chat(
6165
&self,
6266
chat: ChatRequest,
@@ -168,44 +172,47 @@ impl<A: Services, F: CommandInfra> API for ForgeAPI<A, F> {
168172
let forge_app = ForgeApp::new(self.services.clone());
169173
forge_app.logout().await
170174
}
171-
async fn provider(&self) -> anyhow::Result<Provider> {
172-
self.services
173-
.get_provider(self.services.get_app_config().await.unwrap_or_default())
174-
.await
175+
async fn get_provider(&self) -> anyhow::Result<Provider> {
176+
self.services.get_active_provider().await
175177
}
176178

177-
async fn app_config(&self) -> Option<AppConfig> {
178-
self.services.get_app_config().await
179+
async fn set_provider(&self, provider_id: ProviderId) -> anyhow::Result<()> {
180+
self.services.set_active_provider(provider_id).await
179181
}
180182

181183
async fn user_info(&self) -> Result<Option<User>> {
182-
let provider = self.provider().await?;
183-
if let Some(api_key) = provider.key() {
184+
let provider = self.get_provider().await?;
185+
if let Some(ref api_key) = provider.key {
184186
let user_info = self.services.user_info(api_key).await?;
185187
return Ok(Some(user_info));
186188
}
187189
Ok(None)
188190
}
189191

190192
async fn user_usage(&self) -> Result<Option<UserUsage>> {
191-
let provider = self.provider().await?;
192-
if let Some(api_key) = provider.key() {
193+
let provider = self.get_provider().await?;
194+
if let Some(ref api_key) = provider.key {
193195
let user_usage = self.services.user_usage(api_key).await?;
194196
return Ok(Some(user_usage));
195197
}
196198
Ok(None)
197199
}
198200

199201
async fn get_operating_agent(&self) -> Option<AgentId> {
200-
self.services
202+
self.infra
201203
.get_app_config()
202204
.await
203-
.and_then(|config| config.operating_agent)
205+
.ok()?
206+
.and_then(|config| config.active_agent)
204207
}
205208

206209
async fn set_operating_agent(&self, agent_id: AgentId) -> anyhow::Result<()> {
207-
let mut config = self.services.get_app_config().await.unwrap_or_default();
208-
config.operating_agent = Some(agent_id);
209-
self.services.set_app_config(&config).await
210+
let mut config = self.infra.get_app_config().await?.unwrap_or_default();
211+
config.active_agent = Some(agent_id);
212+
self.infra.set_app_config(&config).await
213+
}
214+
215+
async fn get_login_info(&self) -> Result<Option<LoginInfo>> {
216+
self.services.auth_service().get_auth_token().await
210217
}
211218
}

‎crates/forge_app/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ console.workspace = true
2525
derive_more.workspace = true
2626
tempfile.workspace = true
2727
strum.workspace = true
28+
strum_macros.workspace = true
2829
forge_template.workspace = true
2930
merge.workspace = true
3031
convert_case.workspace = true

‎crates/forge_app/src/agent.rs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ use forge_domain::{
66
};
77

88
use crate::tool_registry::ToolRegistry;
9-
use crate::{
10-
AppConfigService, ConversationService, ProviderRegistry, ProviderService, Services,
11-
TemplateService,
12-
};
9+
use crate::{ConversationService, ProviderRegistry, ProviderService, Services, TemplateService};
1310

1411
/// Agent service trait that provides core chat and tool call functionality.
1512
/// This trait abstracts the essential operations needed by the Orchestrator.
@@ -49,8 +46,7 @@ impl<T: Services> AgentService for T {
4946
id: &ModelId,
5047
context: Context,
5148
) -> ResultStream<ChatCompletionMessage, anyhow::Error> {
52-
let config = self.get_app_config().await.unwrap_or_default();
53-
let provider = self.get_provider(config).await?;
49+
let provider = self.get_active_provider().await?;
5450
self.chat(id, context, provider).await
5551
}
5652

‎crates/forge_app/src/app.rs‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ use crate::orch::Orchestrator;
1212
use crate::services::{CustomInstructionsService, TemplateService};
1313
use crate::tool_registry::ToolRegistry;
1414
use crate::{
15-
AgentLoaderService, AppConfigService, AttachmentService, ConversationService,
16-
EnvironmentService, FileDiscoveryService, McpService, ProviderRegistry, ProviderService,
17-
Services, Walker, WorkflowService,
15+
AgentLoaderService, AttachmentService, ConversationService, EnvironmentService,
16+
FileDiscoveryService, McpService, ProviderRegistry, ProviderService, Services, Walker,
17+
WorkflowService,
1818
};
1919

2020
/// ForgeApp handles the core chat functionality by orchestrating various
@@ -51,9 +51,8 @@ impl<S: Services> ForgeApp<S> {
5151
.unwrap_or_default()
5252
.expect("conversation for the request should've been created at this point.");
5353

54-
let config = services.get_app_config().await.unwrap_or_default();
5554
let provider = services
56-
.get_provider(config)
55+
.get_active_provider()
5756
.await
5857
.context("Failed to get provider")?;
5958
let models = services.models(provider).await?;

0 commit comments

Comments
 (0)