stakpak-api 0.3.77

Stakpak: Your DevOps AI Agent. Generate infrastructure code, debug Kubernetes, configure CI/CD, automate deployments, without giving an LLM the keys to production.
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use chrono::{DateTime, Utc};
use rmcp::model::Content;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use stakai::Model;
use stakpak_shared::models::{
    integrations::openai::{ChatMessage, FunctionCall, MessageContent, Role, Tool, ToolCall},
    llm::{LLMInput, LLMMessage, LLMMessageContent, LLMMessageTypedContent, LLMTokenUsage},
};
use std::collections::HashMap;
use uuid::Uuid;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum ApiStreamError {
    AgentInputInvalid(String),
    AgentStateInvalid,
    AgentNotSupported,
    AgentExecutionLimitExceeded,
    AgentInvalidResponseStream,
    InvalidGeneratedCode,
    CopilotError,
    SaveError,
    Unknown(String),
}

impl From<&str> for ApiStreamError {
    fn from(error_str: &str) -> Self {
        match error_str {
            s if s.contains("Agent not supported") => ApiStreamError::AgentNotSupported,
            s if s.contains("Agent state is not valid") => ApiStreamError::AgentStateInvalid,
            s if s.contains("Agent thinking limit exceeded") => {
                ApiStreamError::AgentExecutionLimitExceeded
            }
            s if s.contains("Invalid response stream") => {
                ApiStreamError::AgentInvalidResponseStream
            }
            s if s.contains("Invalid generated code") => ApiStreamError::InvalidGeneratedCode,
            s if s.contains(
                "Our copilot is handling too many requests at this time, please try again later.",
            ) =>
            {
                ApiStreamError::CopilotError
            }
            s if s
                .contains("An error occurred while saving your data. Please try again later.") =>
            {
                ApiStreamError::SaveError
            }
            s if s.contains("Agent input is not valid: ") => {
                ApiStreamError::AgentInputInvalid(s.replace("Agent input is not valid: ", ""))
            }
            _ => ApiStreamError::Unknown(error_str.to_string()),
        }
    }
}

impl From<String> for ApiStreamError {
    fn from(error_str: String) -> Self {
        ApiStreamError::from(error_str.as_str())
    }
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Document {
    pub content: String,
    pub uri: String,
    pub provisioner: ProvisionerType,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct SimpleDocument {
    pub uri: String,
    pub content: String,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Block {
    pub id: Uuid,
    pub provider: String,
    pub provisioner: ProvisionerType,
    pub language: String,
    pub key: String,
    pub digest: u64,
    pub references: Vec<Vec<Segment>>,
    pub kind: String,
    pub r#type: Option<String>,
    pub name: Option<String>,
    pub config: serde_json::Value,
    pub document_uri: String,
    pub code: String,
    pub start_byte: usize,
    pub end_byte: usize,
    pub start_point: Point,
    pub end_point: Point,
    pub state: Option<serde_json::Value>,
    pub updated_at: Option<DateTime<Utc>>,
    pub created_at: Option<DateTime<Utc>>,
    pub dependents: Vec<DependentBlock>,
    pub dependencies: Vec<Dependency>,
    pub api_group_version: Option<ApiGroupVersion>,

    pub generated_summary: Option<String>,
}

impl Block {
    pub fn get_uri(&self) -> String {
        format!(
            "{}#L{}-L{}",
            self.document_uri, self.start_point.row, self.end_point.row
        )
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)]
pub enum ProvisionerType {
    #[serde(rename = "Terraform")]
    Terraform,
    #[serde(rename = "Kubernetes")]
    Kubernetes,
    #[serde(rename = "Dockerfile")]
    Dockerfile,
    #[serde(rename = "GithubActions")]
    GithubActions,
    #[serde(rename = "None")]
    None,
}
impl std::str::FromStr for ProvisionerType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "terraform" => Ok(Self::Terraform),
            "kubernetes" => Ok(Self::Kubernetes),
            "dockerfile" => Ok(Self::Dockerfile),
            "github-actions" => Ok(Self::GithubActions),
            _ => Ok(Self::None),
        }
    }
}
impl std::fmt::Display for ProvisionerType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ProvisionerType::Terraform => write!(f, "terraform"),
            ProvisionerType::Kubernetes => write!(f, "kubernetes"),
            ProvisionerType::Dockerfile => write!(f, "dockerfile"),
            ProvisionerType::GithubActions => write!(f, "github-actions"),
            ProvisionerType::None => write!(f, "none"),
        }
    }
}

#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[serde(untagged)]
pub enum Segment {
    Key(String),
    Index(usize),
}

impl std::fmt::Display for Segment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Segment::Key(key) => write!(f, "{}", key),
            Segment::Index(index) => write!(f, "{}", index),
        }
    }
}
impl std::fmt::Debug for Segment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Segment::Key(key) => write!(f, "{}", key),
            Segment::Index(index) => write!(f, "{}", index),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq)]
pub struct Point {
    pub row: usize,
    pub column: usize,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct DependentBlock {
    pub key: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Dependency {
    pub id: Option<Uuid>,
    pub expression: Option<String>,
    pub from_path: Option<Vec<Segment>>,
    pub to_path: Option<Vec<Segment>>,
    #[serde(default = "Vec::new")]
    pub selectors: Vec<DependencySelector>,
    #[serde(skip_serializing)]
    pub key: Option<String>,
    pub digest: Option<u64>,
    #[serde(default = "Vec::new")]
    pub from: Vec<Segment>,
    pub from_field: Option<Vec<Segment>>,
    pub to_field: Option<Vec<Segment>>,
    pub start_byte: Option<usize>,
    pub end_byte: Option<usize>,
    pub start_point: Option<Point>,
    pub end_point: Option<Point>,
    pub satisfied: bool,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct DependencySelector {
    pub references: Vec<Vec<Segment>>,
    pub operator: DependencySelectorOperator,
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum DependencySelectorOperator {
    Equals,
    NotEquals,
    In,
    NotIn,
    Exists,
    DoesNotExist,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ApiGroupVersion {
    pub alias: String,
    pub group: String,
    pub version: String,
    pub provisioner: ProvisionerType,
    pub status: APIGroupVersionStatus,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum APIGroupVersionStatus {
    #[serde(rename = "UNAVAILABLE")]
    Unavailable,
    #[serde(rename = "PENDING")]
    Pending,
    #[serde(rename = "AVAILABLE")]
    Available,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct BuildCodeIndexInput {
    pub documents: Vec<SimpleDocument>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct IndexError {
    pub uri: String,
    pub message: String,
    pub details: Option<serde_json::Value>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BuildCodeIndexOutput {
    pub blocks: Vec<Block>,
    pub errors: Vec<IndexError>,
    pub warnings: Vec<IndexError>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CodeIndex {
    pub last_updated: DateTime<Utc>,
    pub index: BuildCodeIndexOutput,
}

/// Unified skill type representing knowledge from any source.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Skill {
    /// Display name / identifier
    pub name: String,
    /// Unique identifier — API URI for remote, file path for local
    pub uri: String,
    /// When to use this skill
    pub description: String,
    /// Where this skill comes from
    pub source: SkillSource,
    /// None = metadata only; Some = full content loaded
    pub content: Option<String>,
    /// Classification tags
    pub tags: Vec<String>,
    /// License name or reference to a bundled license file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// Environment requirements (intended product, system packages, network access, etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compatibility: Option<String>,
    /// Arbitrary key-value mapping for additional metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,
    /// Space-delimited list of pre-approved tools the skill may use. (Experimental)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_tools: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum SkillSource {
    Local,
    Remote { provider: RemoteProvider },
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum RemoteProvider {
    Rulebook { visibility: RuleBookVisibility },
    Pak,
}

impl Skill {
    pub fn is_local(&self) -> bool {
        matches!(self.source, SkillSource::Local)
    }

    pub fn is_rulebook(&self) -> bool {
        matches!(
            self.source,
            SkillSource::Remote {
                provider: RemoteProvider::Rulebook { .. }
            }
        )
    }

    pub fn is_pak(&self) -> bool {
        matches!(
            self.source,
            SkillSource::Remote {
                provider: RemoteProvider::Pak
            }
        )
    }

    pub fn to_metadata_text(&self) -> String {
        let source_label = match &self.source {
            SkillSource::Local => "local",
            SkillSource::Remote {
                provider: RemoteProvider::Rulebook { .. },
            } => "remote",
            SkillSource::Remote {
                provider: RemoteProvider::Pak,
            } => "pak",
        };
        let tags_str = if self.tags.is_empty() {
            String::new()
        } else {
            format!(" [{}]", self.tags.join(", "))
        };
        format!(
            "<skill><label>{}</label><name>{}</name><description>{}</description><uri>{}</uri><tags>{}</tags></skill>",
            source_label, self.name, self.description, self.uri, tags_str
        )
    }
}

impl From<ListRuleBook> for Skill {
    fn from(rb: ListRuleBook) -> Self {
        Skill {
            name: rb.uri.clone(),
            uri: rb.uri,
            description: rb.description,
            source: SkillSource::Remote {
                provider: RemoteProvider::Rulebook {
                    visibility: rb.visibility,
                },
            },
            content: None,
            tags: rb.tags,
            license: None,
            compatibility: None,
            metadata: None,
            allowed_tools: None,
        }
    }
}

impl From<RuleBook> for Skill {
    fn from(rb: RuleBook) -> Self {
        Skill {
            name: rb.uri.clone(),
            uri: rb.uri,
            description: rb.description,
            source: SkillSource::Remote {
                provider: RemoteProvider::Rulebook {
                    visibility: rb.visibility,
                },
            },
            content: Some(rb.content),
            tags: rb.tags,
            license: None,
            compatibility: None,
            metadata: None,
            allowed_tools: None,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default)]
#[serde(rename_all = "UPPERCASE")]
pub enum RuleBookVisibility {
    #[default]
    Public,
    Private,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RuleBook {
    pub id: String,
    pub uri: String,
    pub description: String,
    pub content: String,
    pub visibility: RuleBookVisibility,
    pub tags: Vec<String>,
    pub created_at: Option<DateTime<Utc>>,
    pub updated_at: Option<DateTime<Utc>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ToolsCallParams {
    pub name: String,
    pub arguments: Value,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ToolsCallResponse {
    pub content: Vec<Content>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct APIKeyScope {
    pub r#type: String,
    pub name: String,
}

impl std::fmt::Display for APIKeyScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({})", self.name, self.r#type)
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct GetMyAccountResponse {
    pub username: String,
    pub id: String,
    pub first_name: String,
    pub last_name: String,
    pub email: String,
    pub scope: Option<APIKeyScope>,
}

impl GetMyAccountResponse {
    pub fn to_text(&self) -> String {
        format!(
            "ID: {}\nUsername: {}\nName: {} {}\nEmail: {}",
            self.id, self.username, self.first_name, self.last_name, self.email
        )
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ListRuleBook {
    pub id: String,
    pub uri: String,
    pub description: String,
    pub visibility: RuleBookVisibility,
    pub tags: Vec<String>,
    pub created_at: Option<DateTime<Utc>>,
    pub updated_at: Option<DateTime<Utc>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ListRulebooksResponse {
    pub results: Vec<ListRuleBook>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CreateRuleBookInput {
    pub uri: String,
    pub description: String,
    pub content: String,
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<RuleBookVisibility>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CreateRuleBookResponse {
    pub id: String,
}

impl ListRuleBook {
    pub fn to_text(&self) -> String {
        format!(
            "URI: {}\nDescription: {}\nTags: {}\n",
            self.uri,
            self.description,
            self.tags.join(", ")
        )
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SimpleLLMMessage {
    #[serde(rename = "role")]
    pub role: SimpleLLMRole,
    pub content: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SimpleLLMRole {
    User,
    Assistant,
}

impl std::fmt::Display for SimpleLLMRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SimpleLLMRole::User => write!(f, "user"),
            SimpleLLMRole::Assistant => write!(f, "assistant"),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SearchDocsRequest {
    pub keywords: String,
    pub exclude_keywords: Option<String>,
    pub limit: Option<u32>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SearchMemoryRequest {
    pub keywords: Vec<String>,
    pub start_time: Option<DateTime<Utc>>,
    pub end_time: Option<DateTime<Utc>>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SlackReadMessagesRequest {
    pub channel: String,
    pub limit: Option<u32>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SlackReadRepliesRequest {
    pub channel: String,
    pub ts: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SlackSendMessageRequest {
    pub channel: String,
    pub markdown_text: String,
    pub thread_ts: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct AgentState {
    /// The active model to use for inference
    pub active_model: Model,
    pub messages: Vec<ChatMessage>,
    pub tools: Option<Vec<Tool>>,

    pub llm_input: Option<LLMInput>,
    pub llm_output: Option<LLMOutput>,

    /// Metadata for checkpoint persistence (context trimming state, etc.)
    /// Loaded from checkpoint on session resume and saved back after inference
    pub metadata: Option<Value>,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct LLMOutput {
    pub new_message: LLMMessage,
    pub usage: LLMTokenUsage,
}

impl From<&LLMOutput> for ChatMessage {
    fn from(value: &LLMOutput) -> Self {
        let message_content = match &value.new_message.content {
            LLMMessageContent::String(s) => s.clone(),
            LLMMessageContent::List(l) => l
                .iter()
                .map(|c| match c {
                    LLMMessageTypedContent::Text { text } => text.clone(),
                    LLMMessageTypedContent::ToolCall { .. } => String::new(),
                    LLMMessageTypedContent::ToolResult { content, .. } => content.clone(),
                    LLMMessageTypedContent::Image { .. } => String::new(),
                })
                .collect::<Vec<_>>()
                .join("\n"),
        };
        let tool_calls = if let LLMMessageContent::List(items) = &value.new_message.content {
            let calls: Vec<ToolCall> = items
                .iter()
                .filter_map(|item| {
                    if let LLMMessageTypedContent::ToolCall {
                        id,
                        name,
                        args,
                        metadata,
                    } = item
                    {
                        Some(ToolCall {
                            id: id.clone(),
                            r#type: "function".to_string(),
                            function: FunctionCall {
                                name: name.clone(),
                                arguments: args.to_string(),
                            },
                            metadata: metadata.clone(),
                        })
                    } else {
                        None
                    }
                })
                .collect();

            if calls.is_empty() { None } else { Some(calls) }
        } else {
            None
        };
        ChatMessage {
            role: Role::Assistant,
            content: Some(MessageContent::String(message_content)),
            name: None,
            tool_calls,
            tool_call_id: None,
            usage: Some(value.usage.clone()),
            ..Default::default()
        }
    }
}

impl AgentState {
    pub fn new(
        active_model: Model,
        messages: Vec<ChatMessage>,
        tools: Option<Vec<Tool>>,
        metadata: Option<Value>,
    ) -> Self {
        Self {
            active_model,
            messages,
            tools,
            metadata,
            llm_input: None,
            llm_output: None,
        }
    }

    pub fn set_messages(&mut self, messages: Vec<ChatMessage>) {
        self.messages = messages;
    }

    pub fn set_tools(&mut self, tools: Option<Vec<Tool>>) {
        self.tools = tools;
    }

    pub fn set_active_model(&mut self, model: Model) {
        self.active_model = model;
    }

    pub fn set_llm_input(&mut self, llm_input: Option<LLMInput>) {
        self.llm_input = llm_input;
    }

    pub fn set_llm_output(&mut self, new_message: LLMMessage, new_usage: Option<LLMTokenUsage>) {
        self.llm_output = Some(LLMOutput {
            new_message,
            usage: new_usage.unwrap_or_default(),
        });
    }

    pub fn append_new_message(&mut self, new_message: ChatMessage) {
        self.messages.push(new_message);
    }
}