1use std::collections::HashMap;
2use std::ops::Deref;
3use std::sync::{Arc, Mutex, PoisonError, Weak};
4
5use chrono::{DateTime, Utc};
6use serde::{Deserialize, Serialize};
7use serde_json::{Value, json};
8
9use super::versioning::{Repository, Route};
10use crate::billing::PageQuery;
11use crate::error::{Error, Result};
12use crate::parrot::generative::{Content, Text};
13use crate::shared::server::Room;
14
15#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
17pub struct TermsSchedule {
18 pub total: f64,
19 pub upfront: f64,
20 pub duration: f64,
21 pub interval: f64,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
25#[serde(untagged)]
26pub enum Terms {
27 Amount(f64),
28 Schedule(TermsSchedule),
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "UPPERCASE")]
34pub enum TicketStatus {
35 Active,
36 Rejected,
37 Fulfilled,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct Ticket {
42 pub id: u64,
43 pub date: DateTime<Utc>,
44 pub issue: String,
45 pub status: TicketStatus,
46}
47
48#[derive(Clone)]
49pub struct Constitution {
50 pub text: String,
51 pub articles: Vec<String>,
52
53 room: RuntimeRoom,
54}
55
56impl Constitution {
57 pub async fn amend(&mut self, article: &str) -> Result<()> {
58 self.articles.push(article.to_string());
59 self.room
60 .runtime
61 .articles
62 .lock()
63 .unwrap_or_else(PoisonError::into_inner)
64 .push(article.to_string());
65 self.room
66 .update(&json!({ "event": "amend-constitution", "article": article }));
67 Ok(())
68 }
69}
70
71struct Runtime {
72 name: String,
73 model: Text,
74 text: String,
75 articles: Mutex<Vec<String>>,
76 agents: Mutex<HashMap<String, Agent>>,
77}
78
79#[derive(Clone)]
80pub struct RuntimeRoom {
81 room: Room,
82 runtime: Arc<Runtime>,
83}
84
85impl Deref for RuntimeRoom {
86 type Target = Room;
87 fn deref(&self) -> &Room {
88 &self.room
89 }
90}
91
92impl RuntimeRoom {
93 pub fn new(room: Room, state: &Value) -> RuntimeRoom {
95 RuntimeRoom {
96 room,
97 runtime: Arc::new(Runtime {
98 name: state["name"].as_str().unwrap_or_default().to_string(),
99 model: serde_json::from_value(state["model"].clone()).unwrap_or(Text::Auto),
100 text: state["constitution"]["text"]
101 .as_str()
102 .unwrap_or_default()
103 .to_string(),
104 articles: Mutex::new(
105 serde_json::from_value(state["constitution"]["articles"].clone())
106 .unwrap_or_default(),
107 ),
108 agents: Mutex::new(HashMap::new()),
109 }),
110 }
111 }
112
113 pub fn name(&self) -> &str {
114 &self.runtime.name
115 }
116
117 pub fn constitution(&self) -> Constitution {
118 Constitution {
119 text: self.runtime.text.clone(),
120 articles: self
121 .runtime
122 .articles
123 .lock()
124 .unwrap_or_else(PoisonError::into_inner)
125 .clone(),
126 room: self.clone(),
127 }
128 }
129
130 pub fn model(&self) -> Text {
131 self.runtime.model
132 }
133
134 pub fn agents(&self) -> HashMap<String, Agent> {
135 self.runtime
136 .agents
137 .lock()
138 .unwrap_or_else(PoisonError::into_inner)
139 .clone()
140 }
141
142 pub fn update(&self, json: &Value) {
143 self.post(json);
144 }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
149#[serde(rename_all = "UPPERCASE")]
150pub enum AgentStatus {
151 Active,
152 #[default]
153 Idle,
154 Deleted,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub struct TimeRange {
160 pub start: DateTime<Utc>,
161 pub end: DateTime<Utc>,
162 pub max: Option<u32>,
163}
164
165#[derive(Debug, Clone)]
167pub enum TimeRangeOrPage {
168 Range(TimeRange),
169 Page(PageQuery),
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(rename_all = "camelCase")]
175pub struct BalancePoint {
176 pub balance_micros: i64,
177 pub date: DateTime<Utc>,
178}
179
180struct AgentInner {
181 parent: Option<Weak<AgentInner>>,
182 id: String,
183 children: Mutex<Vec<Agent>>,
184 bible: String,
185 status: AgentStatus,
186 repository: Repository,
187}
188
189#[derive(Clone)]
190pub struct Agent(Arc<AgentInner>);
191
192fn not_implemented<T>() -> Result<T> {
193 Err(Error::Message(
194 "Termite routes are not implemented.".to_string(),
195 ))
196}
197
198impl Agent {
199 pub fn new(
201 parent: Option<&Agent>,
202 id: &str,
203 bible: &str,
204 repository: Repository,
205 status: Option<AgentStatus>,
206 ) -> Agent {
207 let agent = Agent(Arc::new(AgentInner {
208 parent: parent.map(|parent| Arc::downgrade(&parent.0)),
209 id: id.to_string(),
210 children: Mutex::new(Vec::new()),
211 bible: bible.to_string(),
212 status: status.unwrap_or_default(),
213 repository,
214 }));
215 if let Some(parent) = parent {
216 parent
217 .0
218 .children
219 .lock()
220 .unwrap_or_else(PoisonError::into_inner)
221 .push(agent.clone());
222 }
223 agent
224 }
225
226 pub fn parent(&self) -> Option<Agent> {
227 self.0.parent.as_ref().and_then(Weak::upgrade).map(Agent)
228 }
229
230 pub fn id(&self) -> &str {
231 &self.0.id
232 }
233
234 pub fn children(&self) -> Vec<Agent> {
235 self.0
236 .children
237 .lock()
238 .unwrap_or_else(PoisonError::into_inner)
239 .clone()
240 }
241
242 pub fn bible(&self) -> &str {
243 &self.0.bible
244 }
245
246 pub fn status(&self) -> AgentStatus {
247 self.0.status
248 }
249
250 pub fn repository(&self) -> &Repository {
251 &self.0.repository
252 }
253
254 pub async fn ticket(&self, _issue: &str) -> Result<Ticket> {
255 not_implemented()
256 }
257
258 pub async fn delete(&self) -> Result<()> {
259 not_implemented()
260 }
261
262 pub async fn balance(&self, _query: TimeRangeOrPage) -> Result<Vec<BalancePoint>> {
263 not_implemented()
264 }
265
266 pub async fn contracts(&self, _query: TimeRangeOrPage) -> Result<Vec<Contract>> {
267 not_implemented()
268 }
269
270 pub async fn loans(&self, _query: TimeRangeOrPage) -> Result<Vec<Loan>> {
271 not_implemented()
272 }
273
274 pub async fn tickets(&self, _query: TimeRangeOrPage) -> Result<Vec<Ticket>> {
275 not_implemented()
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
281#[serde(rename_all = "UPPERCASE")]
282pub enum ContractStatus {
283 #[default]
284 Proposed,
285 Active,
286 Rejected,
287 Countered,
288 Defaulted,
289 Fulfilled,
290}
291
292#[derive(Clone)]
294pub enum ContentOrContract {
295 Content(Content),
296 Contract(Box<Contract>),
297}
298
299#[derive(Debug, Clone)]
301pub struct Validation {
302 pub repository: Repository,
303 pub route: Route,
304}
305
306#[derive(Clone)]
307pub struct Contract {
308 pub parent: RuntimeRoom,
309 pub id: String,
310 pub principal: Agent,
311 pub contractor: Agent,
312
313 pub description: String,
314 pub settlement: Terms,
315 pub status: ContractStatus,
316 pub content: Vec<ContentOrContract>,
317 pub validation: Validation,
318 pub date: DateTime<Utc>,
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
323#[serde(rename_all = "UPPERCASE")]
324pub enum LoanStatus {
325 #[default]
326 Proposed,
327 Active,
328 Rejected,
329 Defaulted,
330 Fulfilled,
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
335pub struct LoanTerms {
336 pub lender: Terms,
337 pub borrower: Terms,
338}
339
340#[derive(Clone)]
341pub struct Loan {
342 pub parent: RuntimeRoom,
343 pub id: String,
344 pub lender: Agent,
345 pub borrower: Agent,
346
347 pub terms: LoanTerms,
348 pub status: LoanStatus,
349 pub date: DateTime<Utc>,
350}