Skip to main content

ironbridge/api/
sdk.rs

1// Copyright (c) 2024-2028 Nervosys LLC
2// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-IronBridge-Commercial
3//! SDK Module
4//!
5//! Provides SDK generation and developer tooling for custom integrations.
6
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9
10// ============================================================================
11// SDK Configuration
12// ============================================================================
13
14/// SDK configuration
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct SdkConfig {
17    /// SDK version
18    pub version: String,
19    /// Base API URL
20    pub base_url: String,
21    /// Supported languages
22    pub languages: Vec<SdkLanguage>,
23    /// API version
24    pub api_version: String,
25}
26
27/// SDK language
28///
29/// `ValueEnum` is derived here rather than mirrored in `cli.rs` on purpose: a
30/// second copy of the variant list is a copy that can fall behind, which is
31/// the same class of bug as the placeholder arm `generate()` used to have.
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, clap::ValueEnum)]
33#[serde(rename_all = "lowercase")]
34pub enum SdkLanguage {
35    #[value(name = "python")]
36    Python,
37    #[value(name = "nodejs")]
38    NodeJs,
39    #[value(name = "go")]
40    Go,
41    #[value(name = "rust")]
42    Rust,
43    #[value(name = "java")]
44    Java,
45    #[value(name = "csharp")]
46    CSharp,
47    #[value(name = "ruby")]
48    Ruby,
49    #[value(name = "php")]
50    Php,
51}
52
53impl SdkLanguage {
54    /// Every language, so callers and tests cannot silently miss one.
55    pub const ALL: [SdkLanguage; 8] = [
56        SdkLanguage::Python,
57        SdkLanguage::NodeJs,
58        SdkLanguage::Go,
59        SdkLanguage::Rust,
60        SdkLanguage::Java,
61        SdkLanguage::CSharp,
62        SdkLanguage::Ruby,
63        SdkLanguage::Php,
64    ];
65}
66
67impl std::fmt::Display for SdkLanguage {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            SdkLanguage::Python => write!(f, "python"),
71            SdkLanguage::NodeJs => write!(f, "nodejs"),
72            SdkLanguage::Go => write!(f, "go"),
73            SdkLanguage::Rust => write!(f, "rust"),
74            SdkLanguage::Java => write!(f, "java"),
75            SdkLanguage::CSharp => write!(f, "csharp"),
76            SdkLanguage::Ruby => write!(f, "ruby"),
77            SdkLanguage::Php => write!(f, "php"),
78        }
79    }
80}
81
82// ============================================================================
83// SDK Templates
84// ============================================================================
85
86/// Python SDK template
87pub const PYTHON_SDK_TEMPLATE: &str = r#"# IronBridge Python SDK
88# Auto-generated - Do not edit directly
89# Version: {{version}}
90
91"""
92IronBridge Python SDK
93
94A Python client library for the IronBridge API.
95
96Usage:
97    from ironbridge import IronBridgeClient
98    
99    client = IronBridgeClient(api_key="your-api-key")
100    sessions = client.sessions.list()
101"""
102
103import os
104import json
105import requests
106from typing import Optional, List, Dict, Any, Union
107from dataclasses import dataclass, field
108from datetime import datetime
109from urllib.parse import urljoin
110
111__version__ = "{{version}}"
112__api_version__ = "{{api_version}}"
113
114
115def _default_base_url() -> str:
116    """The base URL from the environment, falling back to the generated default."""
117    return os.environ.get("IRONBRIDGE_BASE_URL") or "{{base_url}}"
118
119
120def _default_api_key() -> Optional[str]:
121    """The API key from the environment, or None when unauthenticated."""
122    return os.environ.get("IRONBRIDGE_API_KEY") or None
123
124
125@dataclass
126class IronBridgeConfig:
127    """Configuration for IronBridge client."""
128    base_url: str = field(default_factory=_default_base_url)
129    api_key: Optional[str] = field(default_factory=_default_api_key)
130    timeout: int = 30
131    retry_count: int = 3
132    retry_delay: float = 1.0
133
134
135@dataclass
136class Session:
137    """Represents a chat session."""
138    id: str
139    title: str
140    provider: str
141    workspace_id: Optional[str] = None
142    message_count: int = 0
143    token_count: int = 0
144    created_at: Optional[datetime] = None
145    updated_at: Optional[datetime] = None
146    tags: List[str] = field(default_factory=list)
147    archived: bool = False
148
149
150@dataclass
151class Message:
152    """Represents a chat message."""
153    id: str
154    session_id: str
155    role: str
156    content: str
157    model: Optional[str] = None
158    token_count: int = 0
159    created_at: Optional[datetime] = None
160
161
162@dataclass
163class Workspace:
164    """Represents a workspace."""
165    id: str
166    name: str
167    path: str
168    provider: str
169    session_count: int = 0
170    created_at: Optional[datetime] = None
171
172
173class IronBridgeError(Exception):
174    """Base exception for IronBridge errors."""
175    def __init__(self, message: str, status_code: Optional[int] = None, response: Optional[dict] = None):
176        super().__init__(message)
177        self.status_code = status_code
178        self.response = response
179
180
181class AuthenticationError(IronBridgeError):
182    """Authentication failed."""
183    pass
184
185
186class RateLimitError(IronBridgeError):
187    """Rate limit exceeded."""
188    pass
189
190
191class NotFoundError(IronBridgeError):
192    """Resource not found."""
193    pass
194
195
196class ApiClient:
197    """Low-level API client."""
198    
199    def __init__(self, config: IronBridgeConfig):
200        self.config = config
201        self.session = requests.Session()
202        if config.api_key:
203            self.session.headers["Authorization"] = f"Bearer {config.api_key}"
204        self.session.headers["Content-Type"] = "application/json"
205        self.session.headers["User-Agent"] = f"ironbridge-python/{__version__}"
206    
207    def request(self, method: str, path: str, **kwargs) -> dict:
208        """Make an API request."""
209        url = urljoin(self.config.base_url, path)
210        kwargs.setdefault("timeout", self.config.timeout)
211        
212        response = self.session.request(method, url, **kwargs)
213        
214        if response.status_code == 401:
215            raise AuthenticationError("Invalid API key", 401)
216        elif response.status_code == 404:
217            raise NotFoundError("Resource not found", 404)
218        elif response.status_code == 429:
219            raise RateLimitError("Rate limit exceeded", 429)
220        elif response.status_code >= 400:
221            raise IronBridgeError(f"API error: {response.text}", response.status_code)
222        
223        if response.content:
224            return response.json()
225        return {}
226    
227    def get(self, path: str, params: Optional[dict] = None) -> dict:
228        return self.request("GET", path, params=params)
229    
230    def post(self, path: str, data: Optional[dict] = None) -> dict:
231        return self.request("POST", path, json=data)
232    
233    def put(self, path: str, data: Optional[dict] = None) -> dict:
234        return self.request("PUT", path, json=data)
235    
236    def delete(self, path: str) -> dict:
237        return self.request("DELETE", path)
238
239
240class SessionsResource:
241    """Sessions API resource."""
242    
243    def __init__(self, client: ApiClient):
244        self._client = client
245    
246    def list(
247        self,
248        workspace_id: Optional[str] = None,
249        provider: Optional[str] = None,
250        archived: Optional[bool] = None,
251        limit: int = 20,
252        offset: int = 0,
253    ) -> List[Session]:
254        """List sessions."""
255        params = {"limit": limit, "offset": offset}
256        if workspace_id:
257            params["workspace_id"] = workspace_id
258        if provider:
259            params["provider"] = provider
260        if archived is not None:
261            params["archived"] = str(archived).lower()
262        
263        response = self._client.get("/api/sessions", params)
264        return [self._parse_session(s) for s in response.get("sessions", [])]
265    
266    def get(self, session_id: str) -> Session:
267        """Get a session by ID."""
268        response = self._client.get(f"/api/sessions/{session_id}")
269        return self._parse_session(response)
270    
271    def create(self, title: str, provider: str, workspace_id: Optional[str] = None) -> Session:
272        """Create a new session."""
273        data = {"title": title, "provider": provider}
274        if workspace_id:
275            data["workspace_id"] = workspace_id
276        response = self._client.post("/api/sessions", data)
277        return self._parse_session(response)
278    
279    def update(self, session_id: str, **kwargs) -> Session:
280        """Update a session."""
281        response = self._client.put(f"/api/sessions/{session_id}", kwargs)
282        return self._parse_session(response)
283    
284    def delete(self, session_id: str) -> bool:
285        """Delete a session."""
286        self._client.delete(f"/api/sessions/{session_id}")
287        return True
288    
289    def archive(self, session_id: str) -> Session:
290        """Archive a session."""
291        return self.update(session_id, archived=True)
292    
293    def search(self, query: str, limit: int = 20) -> List[Session]:
294        """Search sessions."""
295        response = self._client.get("/api/sessions/search", {"q": query, "limit": limit})
296        return [self._parse_session(s) for s in response.get("sessions", [])]
297    
298    def _parse_session(self, data: dict) -> Session:
299        return Session(
300            id=data["id"],
301            title=data.get("title", "Untitled"),
302            provider=data.get("provider", "unknown"),
303            workspace_id=data.get("workspace_id"),
304            message_count=data.get("message_count", 0),
305            token_count=data.get("token_count", 0),
306            tags=data.get("tags", []),
307            archived=data.get("archived", False),
308        )
309
310
311class WorkspacesResource:
312    """Workspaces API resource."""
313    
314    def __init__(self, client: ApiClient):
315        self._client = client
316    
317    def list(self, limit: int = 20, offset: int = 0) -> List[Workspace]:
318        """List workspaces."""
319        response = self._client.get("/api/workspaces", {"limit": limit, "offset": offset})
320        return [self._parse_workspace(w) for w in response.get("workspaces", [])]
321    
322    def get(self, workspace_id: str) -> Workspace:
323        """Get a workspace by ID."""
324        response = self._client.get(f"/api/workspaces/{workspace_id}")
325        return self._parse_workspace(response)
326    
327    def _parse_workspace(self, data: dict) -> Workspace:
328        return Workspace(
329            id=data["id"],
330            name=data.get("name", ""),
331            path=data.get("path", ""),
332            provider=data.get("provider", ""),
333            session_count=data.get("session_count", 0),
334        )
335
336
337class HarvestResource:
338    """Harvest API resource."""
339    
340    def __init__(self, client: ApiClient):
341        self._client = client
342    
343    def run(self, providers: Optional[List[str]] = None) -> dict:
344        """Run harvest."""
345        data = {}
346        if providers:
347            data["providers"] = providers
348        return self._client.post("/api/harvest", data)
349    
350
351class IronBridgeClient:
352    """Main IronBridge client."""
353    
354    def __init__(
355        self,
356        api_key: Optional[str] = None,
357        base_url: Optional[str] = None,
358        **kwargs
359    ):
360        config = IronBridgeConfig(
361            api_key=api_key or _default_api_key(),
362            base_url=base_url or _default_base_url(),
363            **kwargs
364        )
365        self._api = ApiClient(config)
366        
367        # Resources
368        self.sessions = SessionsResource(self._api)
369        self.workspaces = WorkspacesResource(self._api)
370        self.harvest = HarvestResource(self._api)
371    
372    def health(self) -> dict:
373        """Check API health."""
374        return self._api.get("/api/health")
375    
376    def stats(self) -> dict:
377        """Get statistics."""
378        return self._api.get("/api/stats")
379
380
381# Convenience function
382def create_client(**kwargs) -> IronBridgeClient:
383    """Create a IronBridge client with environment configuration."""
384    return IronBridgeClient(**kwargs)
385"#;
386
387/// Node.js SDK template
388pub const NODEJS_SDK_TEMPLATE: &str = r#"/**
389 * IronBridge Node.js SDK
390 * Auto-generated - Do not edit directly
391 * Version: {{version}}
392 */
393
394const https = require('https');
395const http = require('http');
396const { URL } = require('url');
397
398const VERSION = '{{version}}';
399const API_VERSION = '{{api_version}}';
400
401/**
402 * IronBridge client configuration
403 */
404class IronBridgeConfig {
405  constructor(options = {}) {
406    this.baseUrl = options.baseUrl || process.env.IRONBRIDGE_BASE_URL || '{{base_url}}';
407    this.apiKey = options.apiKey || process.env.IRONBRIDGE_API_KEY;
408    this.timeout = options.timeout || 30000;
409    this.retryCount = options.retryCount || 3;
410  }
411}
412
413/**
414 * Custom error classes
415 */
416class IronBridgeError extends Error {
417  constructor(message, statusCode, response) {
418    super(message);
419    this.name = 'IronBridgeError';
420    this.statusCode = statusCode;
421    this.response = response;
422  }
423}
424
425class AuthenticationError extends IronBridgeError {
426  constructor(message) {
427    super(message, 401);
428    this.name = 'AuthenticationError';
429  }
430}
431
432class NotFoundError extends IronBridgeError {
433  constructor(message) {
434    super(message, 404);
435    this.name = 'NotFoundError';
436  }
437}
438
439class RateLimitError extends IronBridgeError {
440  constructor(message) {
441    super(message, 429);
442    this.name = 'RateLimitError';
443  }
444}
445
446/**
447 * Low-level API client
448 */
449class ApiClient {
450  constructor(config) {
451    this.config = config;
452  }
453
454  async request(method, path, options = {}) {
455    const url = new URL(path, this.config.baseUrl);
456    const isHttps = url.protocol === 'https:';
457    const client = isHttps ? https : http;
458
459    if (options.params) {
460      Object.entries(options.params).forEach(([key, value]) => {
461        if (value !== undefined) {
462          url.searchParams.append(key, String(value));
463        }
464      });
465    }
466
467    const requestOptions = {
468      method,
469      hostname: url.hostname,
470      port: url.port || (isHttps ? 443 : 80),
471      path: url.pathname + url.search,
472      headers: {
473        'Content-Type': 'application/json',
474        'User-Agent': `ironbridge-nodejs/${VERSION}`,
475        ...(this.config.apiKey && { Authorization: `Bearer ${this.config.apiKey}` }),
476      },
477      timeout: this.config.timeout,
478    };
479
480    return new Promise((resolve, reject) => {
481      const req = client.request(requestOptions, (res) => {
482        let data = '';
483        res.on('data', (chunk) => (data += chunk));
484        res.on('end', () => {
485          if (res.statusCode === 401) {
486            reject(new AuthenticationError('Invalid API key'));
487          } else if (res.statusCode === 404) {
488            reject(new NotFoundError('Resource not found'));
489          } else if (res.statusCode === 429) {
490            reject(new RateLimitError('Rate limit exceeded'));
491          } else if (res.statusCode >= 400) {
492            reject(new IronBridgeError(`API error: ${data}`, res.statusCode));
493          } else {
494            resolve(data ? JSON.parse(data) : {});
495          }
496        });
497      });
498
499      req.on('error', reject);
500      req.on('timeout', () => {
501        req.destroy();
502        reject(new IronBridgeError('Request timeout'));
503      });
504
505      if (options.body) {
506        req.write(JSON.stringify(options.body));
507      }
508      req.end();
509    });
510  }
511
512  get(path, params) {
513    return this.request('GET', path, { params });
514  }
515
516  post(path, body) {
517    return this.request('POST', path, { body });
518  }
519
520  put(path, body) {
521    return this.request('PUT', path, { body });
522  }
523
524  delete(path) {
525    return this.request('DELETE', path);
526  }
527}
528
529/**
530 * Sessions resource
531 */
532class SessionsResource {
533  constructor(client) {
534    this._client = client;
535  }
536
537  async list(options = {}) {
538    const params = {
539      limit: options.limit || 20,
540      offset: options.offset || 0,
541      workspace_id: options.workspaceId,
542      provider: options.provider,
543      archived: options.archived,
544    };
545    const response = await this._client.get('/api/sessions', params);
546    return response.sessions || [];
547  }
548
549  async get(sessionId) {
550    return this._client.get(`/api/sessions/${sessionId}`);
551  }
552
553  async create(data) {
554    return this._client.post('/api/sessions', data);
555  }
556
557  async update(sessionId, data) {
558    return this._client.put(`/api/sessions/${sessionId}`, data);
559  }
560
561  async delete(sessionId) {
562    await this._client.delete(`/api/sessions/${sessionId}`);
563    return true;
564  }
565
566  async search(query, limit = 20) {
567    const response = await this._client.get('/api/sessions/search', { q: query, limit });
568    return response.sessions || [];
569  }
570}
571
572/**
573 * Workspaces resource
574 */
575class WorkspacesResource {
576  constructor(client) {
577    this._client = client;
578  }
579
580  async list(options = {}) {
581    const params = {
582      limit: options.limit || 20,
583      offset: options.offset || 0,
584    };
585    const response = await this._client.get('/api/workspaces', params);
586    return response.workspaces || [];
587  }
588
589  async get(workspaceId) {
590    return this._client.get(`/api/workspaces/${workspaceId}`);
591  }
592}
593
594/**
595 * Harvest resource
596 */
597class HarvestResource {
598  constructor(client) {
599    this._client = client;
600  }
601
602  async run(providers) {
603    const data = providers ? { providers } : {};
604    return this._client.post('/api/harvest', data);
605  }
606}
607
608/**
609 * Main IronBridge client
610 */
611class IronBridgeClient {
612  constructor(options = {}) {
613    const config = new IronBridgeConfig(options);
614    this._api = new ApiClient(config);
615
616    this.sessions = new SessionsResource(this._api);
617    this.workspaces = new WorkspacesResource(this._api);
618    this.harvest = new HarvestResource(this._api);
619  }
620
621  async health() {
622    return this._api.get('/api/health');
623  }
624
625  async stats() {
626    return this._api.get('/api/stats');
627  }
628}
629
630module.exports = {
631  IronBridgeClient,
632  IronBridgeConfig,
633  IronBridgeError,
634  AuthenticationError,
635  NotFoundError,
636  RateLimitError,
637  VERSION,
638  API_VERSION,
639};
640"#;
641
642/// Go SDK template
643pub const GO_SDK_TEMPLATE: &str = r#"// IronBridge Go SDK
644// Auto-generated - Do not edit directly
645// Version: {{version}}
646
647package ironbridge
648
649import (
650	"bytes"
651	"encoding/json"
652	"fmt"
653	"io"
654	"net/http"
655	"net/url"
656	"os"
657	"time"
658)
659
660const (
661	Version    = "{{version}}"
662	APIVersion = "{{api_version}}"
663)
664
665// Config holds client configuration
666type Config struct {
667	BaseURL    string
668	APIKey     string
669	Timeout    time.Duration
670	RetryCount int
671}
672
673// DefaultConfig returns default configuration
674func DefaultConfig() *Config {
675	baseURL := os.Getenv("IRONBRIDGE_BASE_URL")
676	if baseURL == "" {
677		baseURL = "{{base_url}}"
678	}
679	return &Config{
680		BaseURL:    baseURL,
681		APIKey:     os.Getenv("IRONBRIDGE_API_KEY"),
682		Timeout:    30 * time.Second,
683		RetryCount: 3,
684	}
685}
686
687// Session represents a chat session
688type Session struct {
689	ID           string    `json:"id"`
690	Title        string    `json:"title"`
691	Provider     string    `json:"provider"`
692	WorkspaceID  *string   `json:"workspace_id,omitempty"`
693	MessageCount int       `json:"message_count"`
694	TokenCount   int       `json:"token_count"`
695	Tags         []string  `json:"tags"`
696	Archived     bool      `json:"archived"`
697	CreatedAt    time.Time `json:"created_at,omitempty"`
698	UpdatedAt    time.Time `json:"updated_at,omitempty"`
699}
700
701// Workspace represents a workspace
702type Workspace struct {
703	ID           string    `json:"id"`
704	Name         string    `json:"name"`
705	Path         string    `json:"path"`
706	Provider     string    `json:"provider"`
707	SessionCount int       `json:"session_count"`
708	CreatedAt    time.Time `json:"created_at,omitempty"`
709}
710
711// Error types
712type IronBridgeError struct {
713	Message    string
714	StatusCode int
715}
716
717func (e *IronBridgeError) Error() string {
718	return fmt.Sprintf("ironbridge: %s (status %d)", e.Message, e.StatusCode)
719}
720
721// Client is the main IronBridge client
722type Client struct {
723	config     *Config
724	httpClient *http.Client
725	Sessions   *SessionsService
726	Workspaces *WorkspacesService
727	Harvest    *HarvestService
728}
729
730// NewClient creates a new IronBridge client
731func NewClient(config *Config) *Client {
732	if config == nil {
733		config = DefaultConfig()
734	}
735	
736	c := &Client{
737		config: config,
738		httpClient: &http.Client{
739			Timeout: config.Timeout,
740		},
741	}
742	
743	c.Sessions = &SessionsService{client: c}
744	c.Workspaces = &WorkspacesService{client: c}
745	c.Harvest = &HarvestService{client: c}
746	
747	return c
748}
749
750func (c *Client) request(method, path string, body interface{}, result interface{}) error {
751	u, err := url.Parse(c.config.BaseURL + path)
752	if err != nil {
753		return err
754	}
755
756	var bodyReader io.Reader
757	if body != nil {
758		b, err := json.Marshal(body)
759		if err != nil {
760			return err
761		}
762		bodyReader = bytes.NewReader(b)
763	}
764
765	req, err := http.NewRequest(method, u.String(), bodyReader)
766	if err != nil {
767		return err
768	}
769
770	req.Header.Set("Content-Type", "application/json")
771	req.Header.Set("User-Agent", fmt.Sprintf("ironbridge-go/%s", Version))
772	if c.config.APIKey != "" {
773		req.Header.Set("Authorization", "Bearer "+c.config.APIKey)
774	}
775
776	resp, err := c.httpClient.Do(req)
777	if err != nil {
778		return err
779	}
780	defer resp.Body.Close()
781
782	if resp.StatusCode >= 400 {
783		return &IronBridgeError{
784			Message:    fmt.Sprintf("API error: %s", resp.Status),
785			StatusCode: resp.StatusCode,
786		}
787	}
788
789	if result != nil {
790		return json.NewDecoder(resp.Body).Decode(result)
791	}
792	return nil
793}
794
795// Health checks API health
796func (c *Client) Health() (map[string]interface{}, error) {
797	var result map[string]interface{}
798	err := c.request("GET", "/api/health", nil, &result)
799	return result, err
800}
801
802// Stats gets statistics
803func (c *Client) Stats() (map[string]interface{}, error) {
804	var result map[string]interface{}
805	err := c.request("GET", "/api/stats", nil, &result)
806	return result, err
807}
808
809// SessionsService handles session operations
810type SessionsService struct {
811	client *Client
812}
813
814// ListOptions for listing resources
815type ListOptions struct {
816	Limit       int
817	Offset      int
818	WorkspaceID string
819	Provider    string
820	Archived    *bool
821}
822
823func (s *SessionsService) List(opts *ListOptions) ([]Session, error) {
824	path := "/api/sessions"
825	if opts != nil {
826		params := url.Values{}
827		if opts.Limit > 0 {
828			params.Set("limit", fmt.Sprintf("%d", opts.Limit))
829		}
830		if opts.Offset > 0 {
831			params.Set("offset", fmt.Sprintf("%d", opts.Offset))
832		}
833		if opts.WorkspaceID != "" {
834			params.Set("workspace_id", opts.WorkspaceID)
835		}
836		if opts.Provider != "" {
837			params.Set("provider", opts.Provider)
838		}
839		if opts.Archived != nil {
840			params.Set("archived", fmt.Sprintf("%t", *opts.Archived))
841		}
842		if len(params) > 0 {
843			path += "?" + params.Encode()
844		}
845	}
846	
847	var result struct {
848		Sessions []Session `json:"sessions"`
849	}
850	err := s.client.request("GET", path, nil, &result)
851	return result.Sessions, err
852}
853
854func (s *SessionsService) Get(id string) (*Session, error) {
855	var session Session
856	err := s.client.request("GET", "/api/sessions/"+id, nil, &session)
857	return &session, err
858}
859
860func (s *SessionsService) Create(title, provider string, workspaceID *string) (*Session, error) {
861	body := map[string]interface{}{
862		"title":    title,
863		"provider": provider,
864	}
865	if workspaceID != nil {
866		body["workspace_id"] = *workspaceID
867	}
868	var session Session
869	err := s.client.request("POST", "/api/sessions", body, &session)
870	return &session, err
871}
872
873func (s *SessionsService) Delete(id string) error {
874	return s.client.request("DELETE", "/api/sessions/"+id, nil, nil)
875}
876
877func (s *SessionsService) Search(query string, limit int) ([]Session, error) {
878	path := fmt.Sprintf("/api/sessions/search?q=%s&limit=%d", url.QueryEscape(query), limit)
879	var result struct {
880		Sessions []Session `json:"sessions"`
881	}
882	err := s.client.request("GET", path, nil, &result)
883	return result.Sessions, err
884}
885
886// WorkspacesService handles workspace operations
887type WorkspacesService struct {
888	client *Client
889}
890
891func (w *WorkspacesService) List(opts *ListOptions) ([]Workspace, error) {
892	path := "/api/workspaces"
893	if opts != nil && (opts.Limit > 0 || opts.Offset > 0) {
894		params := url.Values{}
895		if opts.Limit > 0 {
896			params.Set("limit", fmt.Sprintf("%d", opts.Limit))
897		}
898		if opts.Offset > 0 {
899			params.Set("offset", fmt.Sprintf("%d", opts.Offset))
900		}
901		path += "?" + params.Encode()
902	}
903	
904	var result struct {
905		Workspaces []Workspace `json:"workspaces"`
906	}
907	err := w.client.request("GET", path, nil, &result)
908	return result.Workspaces, err
909}
910
911func (w *WorkspacesService) Get(id string) (*Workspace, error) {
912	var workspace Workspace
913	err := w.client.request("GET", "/api/workspaces/"+id, nil, &workspace)
914	return &workspace, err
915}
916
917// HarvestService handles harvest operations
918type HarvestService struct {
919	client *Client
920}
921
922func (h *HarvestService) Run(providers []string) (map[string]interface{}, error) {
923	body := map[string]interface{}{}
924	if len(providers) > 0 {
925		body["providers"] = providers
926	}
927	var result map[string]interface{}
928	err := h.client.request("POST", "/api/harvest", body, &result)
929	return result, err
930}
931"#;
932
933// ============================================================================
934// Rust SDK
935// ============================================================================
936
937pub const RUST_SDK_TEMPLATE: &str = r##"// IronBridge Rust SDK
938// Auto-generated - Do not edit directly
939// Version: {{version}}
940//
941// Add to Cargo.toml:
942//   reqwest = { version = "0.12", features = ["json"] }
943//   serde = { version = "1", features = ["derive"] }
944//   tokio = { version = "1", features = ["full"] }
945
946use serde::{Deserialize, Serialize};
947use std::time::Duration;
948
949pub const VERSION: &str = "{{version}}";
950pub const API_VERSION: &str = "{{api_version}}";
951
952#[derive(Debug, Clone)]
953pub struct Config {
954    pub base_url: String,
955    pub api_key: Option<String>,
956    pub timeout: Duration,
957}
958
959impl Default for Config {
960    fn default() -> Self {
961        Self {
962            base_url: std::env::var("IRONBRIDGE_BASE_URL")
963                .unwrap_or_else(|_| "{{base_url}}".to_string()),
964            api_key: std::env::var("IRONBRIDGE_API_KEY").ok().filter(|k| !k.is_empty()),
965            timeout: Duration::from_secs(30),
966        }
967    }
968}
969
970#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct Session {
972    pub id: String,
973    #[serde(default)]
974    pub title: String,
975    #[serde(default)]
976    pub provider: String,
977    #[serde(default)]
978    pub message_count: i64,
979}
980
981#[derive(Debug, Clone, Serialize, Deserialize)]
982pub struct Workspace {
983    pub id: String,
984    #[serde(default)]
985    pub name: String,
986    #[serde(default)]
987    pub path: String,
988}
989
990#[derive(Debug)]
991pub enum Error {
992    Http(reqwest::Error),
993    Api { status: u16, message: String },
994}
995
996impl std::fmt::Display for Error {
997    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
998        match self {
999            Error::Http(e) => write!(f, "ironbridge: transport error: {e}"),
1000            Error::Api { status, message } => write!(f, "ironbridge: API error {status}: {message}"),
1001        }
1002    }
1003}
1004
1005impl std::error::Error for Error {}
1006
1007impl From<reqwest::Error> for Error {
1008    fn from(e: reqwest::Error) -> Self {
1009        Error::Http(e)
1010    }
1011}
1012
1013pub struct Client {
1014    config: Config,
1015    http: reqwest::Client,
1016}
1017
1018impl Client {
1019    pub fn new(config: Config) -> Result<Self, Error> {
1020        let http = reqwest::Client::builder()
1021            .timeout(config.timeout)
1022            .user_agent(format!("ironbridge-rust/{VERSION}"))
1023            .build()?;
1024        Ok(Self { config, http })
1025    }
1026
1027    async fn get(&self, path: &str) -> Result<serde_json::Value, Error> {
1028        self.send(self.http.get(format!("{}{}", self.config.base_url, path)))
1029            .await
1030    }
1031
1032    async fn post(&self, path: &str, body: serde_json::Value) -> Result<serde_json::Value, Error> {
1033        self.send(
1034            self.http
1035                .post(format!("{}{}", self.config.base_url, path))
1036                .json(&body),
1037        )
1038        .await
1039    }
1040
1041    async fn send(&self, mut req: reqwest::RequestBuilder) -> Result<serde_json::Value, Error> {
1042        if let Some(key) = &self.config.api_key {
1043            req = req.bearer_auth(key);
1044        }
1045        let resp = req.send().await?;
1046        let status = resp.status();
1047        let text = resp.text().await.unwrap_or_default();
1048        if !status.is_success() {
1049            return Err(Error::Api {
1050                status: status.as_u16(),
1051                message: text,
1052            });
1053        }
1054        Ok(serde_json::from_str(&text).unwrap_or(serde_json::Value::Null))
1055    }
1056
1057    pub async fn health(&self) -> Result<serde_json::Value, Error> {
1058        self.get("/api/health").await
1059    }
1060
1061    pub async fn stats(&self) -> Result<serde_json::Value, Error> {
1062        self.get("/api/stats").await
1063    }
1064
1065    pub async fn list_sessions(&self, limit: Option<u32>) -> Result<serde_json::Value, Error> {
1066        match limit {
1067            Some(n) => self.get(&format!("/api/sessions?limit={n}")).await,
1068            None => self.get("/api/sessions").await,
1069        }
1070    }
1071
1072    pub async fn get_session(&self, id: &str) -> Result<serde_json::Value, Error> {
1073        self.get(&format!("/api/sessions/{id}")).await
1074    }
1075
1076    pub async fn search_sessions(&self, query: &str) -> Result<serde_json::Value, Error> {
1077        self.get(&format!(
1078            "/api/sessions/search?q={}",
1079            urlencoding_encode(query)
1080        ))
1081        .await
1082    }
1083
1084    pub async fn list_workspaces(&self) -> Result<serde_json::Value, Error> {
1085        self.get("/api/workspaces").await
1086    }
1087
1088    pub async fn get_workspace(&self, id: &str) -> Result<serde_json::Value, Error> {
1089        self.get(&format!("/api/workspaces/{id}")).await
1090    }
1091
1092    pub async fn harvest(&self) -> Result<serde_json::Value, Error> {
1093        self.post("/api/harvest", serde_json::json!({})).await
1094    }
1095}
1096
1097/// Percent-encode a query value without pulling in another dependency.
1098fn urlencoding_encode(s: &str) -> String {
1099    let mut out = String::with_capacity(s.len());
1100    for b in s.as_bytes() {
1101        match b {
1102            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
1103                out.push(*b as char)
1104            }
1105            _ => out.push_str(&format!("%{b:02X}")),
1106        }
1107    }
1108    out
1109}
1110"##;
1111
1112// ============================================================================
1113// Java SDK
1114// ============================================================================
1115
1116pub const JAVA_SDK_TEMPLATE: &str = r#"// IronBridge Java SDK
1117// Auto-generated - Do not edit directly
1118// Version: {{version}}
1119//
1120// Requires Java 11+ (java.net.http). No external dependencies.
1121
1122package ai.nervosys.ironbridge;
1123
1124import java.net.URI;
1125import java.net.URLEncoder;
1126import java.net.http.HttpClient;
1127import java.net.http.HttpRequest;
1128import java.net.http.HttpResponse;
1129import java.nio.charset.StandardCharsets;
1130import java.time.Duration;
1131
1132public class IronBridge {
1133    public static final String VERSION = "{{version}}";
1134    public static final String API_VERSION = "{{api_version}}";
1135
1136    public static class Config {
1137        public String baseUrl;
1138        public String apiKey;
1139        public Duration timeout = Duration.ofSeconds(30);
1140
1141        public Config() {
1142            String env = System.getenv("IRONBRIDGE_BASE_URL");
1143            this.baseUrl = (env == null || env.isEmpty()) ? "{{base_url}}" : env;
1144            this.apiKey = System.getenv("IRONBRIDGE_API_KEY");
1145        }
1146    }
1147
1148    /** Thrown for any non-2xx response; carries the status so callers can branch. */
1149    public static class IronBridgeException extends RuntimeException {
1150        public final int statusCode;
1151
1152        public IronBridgeException(String message, int statusCode) {
1153            super("ironbridge: " + message + " (status " + statusCode + ")");
1154            this.statusCode = statusCode;
1155        }
1156    }
1157
1158    public static class Client {
1159        private final Config config;
1160        private final HttpClient http;
1161
1162        public Client(Config config) {
1163            this.config = config == null ? new Config() : config;
1164            this.http = HttpClient.newBuilder().connectTimeout(this.config.timeout).build();
1165        }
1166
1167        private String send(HttpRequest.Builder builder) {
1168            builder.header("Content-Type", "application/json");
1169            builder.header("User-Agent", "ironbridge-java/" + VERSION);
1170            if (config.apiKey != null && !config.apiKey.isEmpty()) {
1171                builder.header("Authorization", "Bearer " + config.apiKey);
1172            }
1173            try {
1174                HttpResponse<String> resp =
1175                        http.send(builder.build(), HttpResponse.BodyHandlers.ofString());
1176                if (resp.statusCode() >= 400) {
1177                    throw new IronBridgeException(resp.body(), resp.statusCode());
1178                }
1179                return resp.body();
1180            } catch (IronBridgeException e) {
1181                throw e;
1182            } catch (Exception e) {
1183                throw new RuntimeException("ironbridge: request failed", e);
1184            }
1185        }
1186
1187        private String get(String path) {
1188            return send(HttpRequest.newBuilder().uri(URI.create(config.baseUrl + path)).GET());
1189        }
1190
1191        private String post(String path, String jsonBody) {
1192            return send(HttpRequest.newBuilder()
1193                    .uri(URI.create(config.baseUrl + path))
1194                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody)));
1195        }
1196
1197        public String health() {
1198            return get("/api/health");
1199        }
1200
1201        public String stats() {
1202            return get("/api/stats");
1203        }
1204
1205        public String listSessions() {
1206            return get("/api/sessions");
1207        }
1208
1209        public String getSession(String id) {
1210            return get("/api/sessions/" + id);
1211        }
1212
1213        public String searchSessions(String query) {
1214            return get("/api/sessions/search?q="
1215                    + URLEncoder.encode(query, StandardCharsets.UTF_8));
1216        }
1217
1218        public String listWorkspaces() {
1219            return get("/api/workspaces");
1220        }
1221
1222        public String getWorkspace(String id) {
1223            return get("/api/workspaces/" + id);
1224        }
1225
1226        public String harvest() {
1227            return post("/api/harvest", "{}");
1228        }
1229    }
1230}
1231"#;
1232
1233// ============================================================================
1234// C# SDK
1235// ============================================================================
1236
1237pub const CSHARP_SDK_TEMPLATE: &str = r#"// IronBridge C# SDK
1238// Auto-generated - Do not edit directly
1239// Version: {{version}}
1240//
1241// Targets .NET 6+. No external dependencies.
1242
1243using System;
1244using System.Net.Http;
1245using System.Net.Http.Headers;
1246using System.Threading.Tasks;
1247
1248namespace Nervosys.IronBridge
1249{
1250    public class IronBridgeConfig
1251    {
1252        public string BaseUrl { get; set; }
1253
1254        /// <summary>Null when unauthenticated, which is a supported state.</summary>
1255        public string? ApiKey { get; set; }
1256        public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30);
1257
1258        public IronBridgeConfig()
1259        {
1260            var env = Environment.GetEnvironmentVariable("IRONBRIDGE_BASE_URL");
1261            BaseUrl = string.IsNullOrEmpty(env) ? "{{base_url}}" : env;
1262            ApiKey = Environment.GetEnvironmentVariable("IRONBRIDGE_API_KEY");
1263        }
1264    }
1265
1266    /// <summary>Thrown for any non-2xx response; carries the status code.</summary>
1267    public class IronBridgeException : Exception
1268    {
1269        public int StatusCode { get; }
1270
1271        public IronBridgeException(string message, int statusCode)
1272            : base($"ironbridge: {message} (status {statusCode})")
1273        {
1274            StatusCode = statusCode;
1275        }
1276    }
1277
1278    public class IronBridgeClient : IDisposable
1279    {
1280        public const string Version = "{{version}}";
1281        public const string ApiVersion = "{{api_version}}";
1282
1283        private readonly IronBridgeConfig _config;
1284        private readonly HttpClient _http;
1285
1286        public IronBridgeClient(IronBridgeConfig? config = null)
1287        {
1288            _config = config ?? new IronBridgeConfig();
1289            _http = new HttpClient { Timeout = _config.Timeout };
1290            _http.DefaultRequestHeaders.UserAgent.ParseAdd($"ironbridge-csharp/{Version}");
1291            if (!string.IsNullOrEmpty(_config.ApiKey))
1292            {
1293                _http.DefaultRequestHeaders.Authorization =
1294                    new AuthenticationHeaderValue("Bearer", _config.ApiKey);
1295            }
1296        }
1297
1298        private async Task<string> SendAsync(HttpRequestMessage request)
1299        {
1300            var response = await _http.SendAsync(request).ConfigureAwait(false);
1301            var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
1302            if (!response.IsSuccessStatusCode)
1303            {
1304                throw new IronBridgeException(body, (int)response.StatusCode);
1305            }
1306            return body;
1307        }
1308
1309        private Task<string> GetAsync(string path) =>
1310            SendAsync(new HttpRequestMessage(HttpMethod.Get, _config.BaseUrl + path));
1311
1312        private Task<string> PostAsync(string path, string json) =>
1313            SendAsync(new HttpRequestMessage(HttpMethod.Post, _config.BaseUrl + path)
1314            {
1315                Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
1316            });
1317
1318        public Task<string> HealthAsync() => GetAsync("/api/health");
1319
1320        public Task<string> StatsAsync() => GetAsync("/api/stats");
1321
1322        public Task<string> ListSessionsAsync() => GetAsync("/api/sessions");
1323
1324        public Task<string> GetSessionAsync(string id) => GetAsync("/api/sessions/" + id);
1325
1326        public Task<string> SearchSessionsAsync(string query) =>
1327            GetAsync("/api/sessions/search?q=" + Uri.EscapeDataString(query));
1328
1329        public Task<string> ListWorkspacesAsync() => GetAsync("/api/workspaces");
1330
1331        public Task<string> GetWorkspaceAsync(string id) => GetAsync("/api/workspaces/" + id);
1332
1333        public Task<string> HarvestAsync() => PostAsync("/api/harvest", "{}");
1334
1335        public void Dispose() => _http.Dispose();
1336    }
1337}
1338"#;
1339
1340// ============================================================================
1341// Ruby SDK
1342// ============================================================================
1343
1344pub const RUBY_SDK_TEMPLATE: &str = r#"# IronBridge Ruby SDK
1345# Auto-generated - Do not edit directly
1346# Version: {{version}}
1347#
1348# Standard library only.
1349
1350require 'net/http'
1351require 'uri'
1352require 'json'
1353
1354module IronBridge
1355  VERSION = '{{version}}'.freeze
1356  API_VERSION = '{{api_version}}'.freeze
1357
1358  # Raised for any non-2xx response. Carries the status so callers can branch.
1359  class Error < StandardError
1360    attr_reader :status_code
1361
1362    def initialize(message, status_code)
1363      super("ironbridge: #{message} (status #{status_code})")
1364      @status_code = status_code
1365    end
1366  end
1367
1368  class Config
1369    attr_accessor :base_url, :api_key, :timeout
1370
1371    def initialize(base_url: nil, api_key: nil, timeout: 30)
1372      @base_url = base_url || ENV['IRONBRIDGE_BASE_URL'] || '{{base_url}}'
1373      @api_key = api_key || ENV['IRONBRIDGE_API_KEY']
1374      @timeout = timeout
1375    end
1376  end
1377
1378  class Client
1379    def initialize(config = nil)
1380      @config = config || Config.new
1381    end
1382
1383    def health
1384      get('/api/health')
1385    end
1386
1387    def stats
1388      get('/api/stats')
1389    end
1390
1391    def list_sessions(limit: nil)
1392      path = '/api/sessions'
1393      path += "?limit=#{limit}" if limit
1394      get(path)
1395    end
1396
1397    def get_session(id)
1398      get("/api/sessions/#{id}")
1399    end
1400
1401    def search_sessions(query)
1402      get("/api/sessions/search?q=#{URI.encode_www_form_component(query)}")
1403    end
1404
1405    def list_workspaces
1406      get('/api/workspaces')
1407    end
1408
1409    def get_workspace(id)
1410      get("/api/workspaces/#{id}")
1411    end
1412
1413    def harvest
1414      post('/api/harvest', {})
1415    end
1416
1417    private
1418
1419    def get(path)
1420      uri = URI.parse(@config.base_url + path)
1421      send_request(Net::HTTP::Get.new(uri), uri)
1422    end
1423
1424    def post(path, body)
1425      uri = URI.parse(@config.base_url + path)
1426      request = Net::HTTP::Post.new(uri)
1427      request.body = JSON.generate(body)
1428      send_request(request, uri)
1429    end
1430
1431    def send_request(request, uri)
1432      request['Content-Type'] = 'application/json'
1433      request['User-Agent'] = "ironbridge-ruby/#{VERSION}"
1434      request['Authorization'] = "Bearer #{@config.api_key}" if @config.api_key
1435
1436      response = Net::HTTP.start(uri.hostname, uri.port,
1437                                 use_ssl: uri.scheme == 'https',
1438                                 read_timeout: @config.timeout) do |http|
1439        http.request(request)
1440      end
1441
1442      raise Error.new(response.body, response.code.to_i) if response.code.to_i >= 400
1443
1444      response.body.empty? ? nil : JSON.parse(response.body)
1445    end
1446  end
1447end
1448"#;
1449
1450// ============================================================================
1451// PHP SDK
1452// ============================================================================
1453
1454pub const PHP_SDK_TEMPLATE: &str = r#"<?php
1455// IronBridge PHP SDK
1456// Auto-generated - Do not edit directly
1457// Version: {{version}}
1458//
1459// Requires PHP 7.4+ with ext-curl and ext-json.
1460
1461namespace Nervosys\IronBridge;
1462
1463/** Thrown for any non-2xx response; carries the status so callers can branch. */
1464class IronBridgeException extends \RuntimeException
1465{
1466    public int $statusCode;
1467
1468    public function __construct(string $message, int $statusCode)
1469    {
1470        parent::__construct("ironbridge: {$message} (status {$statusCode})");
1471        $this->statusCode = $statusCode;
1472    }
1473}
1474
1475class Config
1476{
1477    public string $baseUrl;
1478    public ?string $apiKey;
1479    public int $timeout;
1480
1481    public function __construct(?string $baseUrl = null, ?string $apiKey = null, int $timeout = 30)
1482    {
1483        $this->baseUrl = $baseUrl ?: (getenv('IRONBRIDGE_BASE_URL') ?: '{{base_url}}');
1484        $this->apiKey = $apiKey ?: (getenv('IRONBRIDGE_API_KEY') ?: null);
1485        $this->timeout = $timeout;
1486    }
1487}
1488
1489class Client
1490{
1491    public const VERSION = '{{version}}';
1492    public const API_VERSION = '{{api_version}}';
1493
1494    private Config $config;
1495
1496    public function __construct(?Config $config = null)
1497    {
1498        $this->config = $config ?? new Config();
1499    }
1500
1501    public function health(): array
1502    {
1503        return $this->get('/api/health');
1504    }
1505
1506    public function stats(): array
1507    {
1508        return $this->get('/api/stats');
1509    }
1510
1511    public function listSessions(?int $limit = null): array
1512    {
1513        $path = '/api/sessions';
1514        if ($limit !== null) {
1515            $path .= '?limit=' . $limit;
1516        }
1517        return $this->get($path);
1518    }
1519
1520    public function getSession(string $id): array
1521    {
1522        return $this->get('/api/sessions/' . rawurlencode($id));
1523    }
1524
1525    public function searchSessions(string $query): array
1526    {
1527        return $this->get('/api/sessions/search?q=' . rawurlencode($query));
1528    }
1529
1530    public function listWorkspaces(): array
1531    {
1532        return $this->get('/api/workspaces');
1533    }
1534
1535    public function getWorkspace(string $id): array
1536    {
1537        return $this->get('/api/workspaces/' . rawurlencode($id));
1538    }
1539
1540    public function harvest(): array
1541    {
1542        return $this->post('/api/harvest', []);
1543    }
1544
1545    private function get(string $path): array
1546    {
1547        return $this->send('GET', $path, null);
1548    }
1549
1550    private function post(string $path, array $body): array
1551    {
1552        return $this->send('POST', $path, $body);
1553    }
1554
1555    private function send(string $method, string $path, ?array $body): array
1556    {
1557        $headers = [
1558            'Content-Type: application/json',
1559            'User-Agent: ironbridge-php/' . self::VERSION,
1560        ];
1561        if ($this->config->apiKey) {
1562            $headers[] = 'Authorization: Bearer ' . $this->config->apiKey;
1563        }
1564
1565        $ch = curl_init($this->config->baseUrl . $path);
1566        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1567        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
1568        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
1569        curl_setopt($ch, CURLOPT_TIMEOUT, $this->config->timeout);
1570        if ($body !== null) {
1571            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object) $body));
1572        }
1573
1574        $responseBody = curl_exec($ch);
1575        if ($responseBody === false) {
1576            $error = curl_error($ch);
1577            curl_close($ch);
1578            throw new \RuntimeException('ironbridge: request failed: ' . $error);
1579        }
1580        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
1581        curl_close($ch);
1582
1583        if ($status >= 400) {
1584            throw new IronBridgeException((string) $responseBody, $status);
1585        }
1586
1587        $decoded = json_decode((string) $responseBody, true);
1588        return is_array($decoded) ? $decoded : [];
1589    }
1590}
1591"#;
1592// ============================================================================
1593// SDK Generator
1594// ============================================================================
1595
1596/// SDK generator
1597pub struct SdkGenerator {
1598    config: SdkConfig,
1599}
1600
1601impl SdkGenerator {
1602    /// Create a new SDK generator
1603    pub fn new(config: SdkConfig) -> Self {
1604        Self { config }
1605    }
1606
1607    /// Generate SDK for a language
1608    ///
1609    /// Matched exhaustively on purpose. The arm here used to be `_ =>
1610    /// format!("// SDK for {language} not yet implemented")`, which returned a
1611    /// comment where a caller expected a library: five of the eight languages
1612    /// silently produced a one-line file. Listing every variant means adding a
1613    /// language fails to compile until it has a template.
1614    pub fn generate(&self, language: SdkLanguage) -> String {
1615        let template = match language {
1616            SdkLanguage::Python => PYTHON_SDK_TEMPLATE,
1617            SdkLanguage::NodeJs => NODEJS_SDK_TEMPLATE,
1618            SdkLanguage::Go => GO_SDK_TEMPLATE,
1619            SdkLanguage::Rust => RUST_SDK_TEMPLATE,
1620            SdkLanguage::Java => JAVA_SDK_TEMPLATE,
1621            SdkLanguage::CSharp => CSHARP_SDK_TEMPLATE,
1622            SdkLanguage::Ruby => RUBY_SDK_TEMPLATE,
1623            SdkLanguage::Php => PHP_SDK_TEMPLATE,
1624        };
1625
1626        template
1627            .replace("{{version}}", &self.config.version)
1628            .replace("{{api_version}}", &self.config.api_version)
1629            .replace("{{base_url}}", &self.config.base_url)
1630    }
1631
1632    /// Generate all SDKs
1633    pub fn generate_all(&self) -> HashMap<SdkLanguage, String> {
1634        self.config
1635            .languages
1636            .iter()
1637            .map(|lang| (lang.clone(), self.generate(lang.clone())))
1638            .collect()
1639    }
1640
1641    /// Get SDK file name for language
1642    pub fn get_filename(&self, language: &SdkLanguage) -> String {
1643        match language {
1644            SdkLanguage::Python => "ironbridge.py".to_string(),
1645            SdkLanguage::NodeJs => "ironbridge.js".to_string(),
1646            SdkLanguage::Go => "ironbridge.go".to_string(),
1647            SdkLanguage::Rust => "ironbridge.rs".to_string(),
1648            SdkLanguage::Java => "IronBridge.java".to_string(),
1649            SdkLanguage::CSharp => "IronBridge.cs".to_string(),
1650            SdkLanguage::Ruby => "ironbridge.rb".to_string(),
1651            SdkLanguage::Php => "IronBridge.php".to_string(),
1652        }
1653    }
1654}
1655
1656impl Default for SdkConfig {
1657    fn default() -> Self {
1658        Self {
1659            version: "1.0.0".to_string(),
1660            base_url: "http://localhost:8787".to_string(),
1661            languages: SdkLanguage::ALL.to_vec(),
1662            api_version: "v1".to_string(),
1663        }
1664    }
1665}
1666
1667#[cfg(test)]
1668mod tests {
1669    use super::*;
1670
1671    #[test]
1672    fn test_sdk_generation() {
1673        let config = SdkConfig::default();
1674        let generator = SdkGenerator::new(config);
1675
1676        let python_sdk = generator.generate(SdkLanguage::Python);
1677        assert!(python_sdk.contains("class IronBridgeClient"));
1678        assert!(python_sdk.contains("1.0.0"));
1679
1680        let nodejs_sdk = generator.generate(SdkLanguage::NodeJs);
1681        assert!(nodejs_sdk.contains("class IronBridgeClient"));
1682
1683        let go_sdk = generator.generate(SdkLanguage::Go);
1684        assert!(go_sdk.contains("type Client struct"));
1685    }
1686
1687    fn generated(language: SdkLanguage) -> String {
1688        SdkGenerator::new(SdkConfig::default()).generate(language)
1689    }
1690
1691    /// Five of the eight languages used to return
1692    /// `// SDK for rust not yet implemented` -- a *string*, not an error, so a
1693    /// caller wrote a one-line file and found out later.
1694    #[test]
1695    fn every_language_generates_a_real_sdk() {
1696        for language in SdkLanguage::ALL {
1697            let sdk = generated(language.clone());
1698            assert!(
1699                !sdk.contains("not yet implemented"),
1700                "{language} still returns a placeholder"
1701            );
1702            assert!(
1703                sdk.len() > 500,
1704                "{language} produced {} bytes, which is not a library",
1705                sdk.len()
1706            );
1707        }
1708    }
1709
1710    /// An unsubstituted `{{version}}` would ship into generated source, where
1711    /// it is a syntax error in some of these languages and a wrong value in
1712    /// the rest.
1713    #[test]
1714    fn no_placeholder_survives_generation() {
1715        for language in SdkLanguage::ALL {
1716            let sdk = generated(language.clone());
1717            assert!(
1718                !sdk.contains("{{"),
1719                "{language} left an unsubstituted placeholder"
1720            );
1721            assert!(
1722                sdk.contains("1.0.0"),
1723                "{language} did not get the version substituted"
1724            );
1725        }
1726    }
1727
1728    /// Every SDK must reach the API the same way, or a client library becomes
1729    /// a per-language guess about what the server exposes.
1730    #[test]
1731    fn every_sdk_talks_to_the_same_api_surface() {
1732        for language in SdkLanguage::ALL {
1733            let sdk = generated(language.clone());
1734            for path in [
1735                "/api/health",
1736                "/api/stats",
1737                "/api/sessions",
1738                "/api/workspaces",
1739            ] {
1740                assert!(sdk.contains(path), "{language} never calls {path}");
1741            }
1742            assert!(
1743                sdk.contains("IRONBRIDGE_BASE_URL") && sdk.contains("IRONBRIDGE_API_KEY"),
1744                "{language} ignores the environment configuration the others honour"
1745            );
1746        }
1747    }
1748
1749    /// The paths the SDKs call must be paths the server routes.
1750    ///
1751    /// This is not hypothetical: every SDK called `/health`, which 404s -- the
1752    /// route is inside the `/api` scope -- and `/api/harvest/status`, which
1753    /// does not exist at all. Both shipped. Checking against `openapi.yaml`,
1754    /// which its own tests hold to the running server, stops that recurring.
1755    #[test]
1756    fn sdk_paths_exist_in_the_openapi_spec() {
1757        let spec: serde_json::Value =
1758            serde_yaml::from_str(include_str!("../../openapi.yaml")).expect("spec parses");
1759        let paths = spec["paths"].as_object().expect("spec has paths");
1760
1761        // Spec paths are relative to a `/api` server base unless the operation
1762        // overrides it, so compare on the `/api`-prefixed form.
1763        let documented: std::collections::HashSet<String> =
1764            paths.keys().map(|p| format!("/api{p}")).collect();
1765
1766        let re = regex::Regex::new(r#"/api/[a-z0-9/_-]+"#).expect("regex");
1767        for language in SdkLanguage::ALL {
1768            let sdk = generated(language.clone());
1769            for m in re.find_iter(&sdk) {
1770                let called = m.as_str().trim_end_matches('/');
1771                // Ignore prefixes that are built up before an id is appended.
1772                if called.ends_with("/sessions") || called.ends_with("/workspaces") {
1773                    // still a real path; fall through to the check
1774                }
1775                assert!(
1776                    documented.contains(called),
1777                    "{language} calls {called}, which openapi.yaml does not document"
1778                );
1779            }
1780        }
1781    }
1782}