a3s 0.10.6

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
mod model;
mod storage;

use std::collections::BTreeMap;
use std::fmt;
#[cfg(test)]
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use thiserror::Error;
use tokio::sync::Mutex;

use super::credential_store::CredentialStoreError;
use a3s_boot::ilink::SecretValue;
pub(super) use model::{
    IdempotencyState, InboundMessage, InboxRecord, InboxState, OutboundDraft, OutboundRecord,
    OutboundState, RemoteListContext, RemoteListKind, RemoteSelection,
};
use model::{JournalRecord, RuntimeEvent, RuntimeModelError, RuntimeState};

#[derive(Clone)]
pub(super) struct WeixinRuntimeStore {
    inner: Arc<RuntimeStoreInner>,
}

struct RuntimeStoreInner {
    directory: PathBuf,
    state: Mutex<RuntimeState>,
    poisoned: AtomicBool,
    _account_lock: std::fs::File,
}

impl WeixinRuntimeStore {
    pub(super) async fn open(directory: impl Into<PathBuf>) -> Result<Self, RuntimeStoreError> {
        let directory = directory.into();
        let open_directory = directory.clone();
        let opened = tokio::task::spawn_blocking(move || storage::open_runtime(&open_directory))
            .await
            .map_err(|_| RuntimeStoreError::TaskJoin)??;
        Ok(Self {
            inner: Arc::new(RuntimeStoreInner {
                directory,
                state: Mutex::new(opened.state),
                poisoned: AtomicBool::new(false),
                _account_lock: opened.account_lock,
            }),
        })
    }

    pub(super) async fn checkpoint(&self) -> RuntimeCheckpoint {
        let state = self.inner.state.lock().await;
        RuntimeCheckpoint::from_state(&state)
    }

    pub(super) async fn stage_inbound(
        &self,
        cursor: SecretValue,
        messages: Vec<InboundMessage>,
    ) -> Result<Vec<InboxRecord>, RuntimeStoreError> {
        self.append(RuntimeEvent::StageInboundBatch { cursor, messages })
            .await?;
        let mut staged = self
            .checkpoint()
            .await
            .inbox
            .into_values()
            .filter(|record| record.state == InboxState::Staged)
            .collect::<Vec<_>>();
        staged.sort_by(|left, right| {
            left.staged_sequence
                .cmp(&right.staged_sequence)
                .then_with(|| left.staged_index.cmp(&right.staged_index))
                .then_with(|| left.message.key.cmp(&right.message.key))
        });
        Ok(staged)
    }

    pub(super) async fn set_inbox_state(
        &self,
        key: impl Into<String>,
        state: InboxState,
    ) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::SetInboxState {
            key: key.into(),
            state,
        })
        .await
    }

    #[cfg(test)]
    pub(super) async fn queue_outbound(
        &self,
        draft: OutboundDraft,
    ) -> Result<OutboundRecord, RuntimeStoreError> {
        let message = outbound_record(draft, None);
        self.append(RuntimeEvent::QueueOutbound {
            message: message.clone(),
        })
        .await?;
        Ok(message)
    }

    pub(super) async fn queue_outbound_for_inbox(
        &self,
        key: impl Into<String>,
        draft: OutboundDraft,
    ) -> Result<OutboundRecord, RuntimeStoreError> {
        let key = key.into();
        let source_order = self
            .checkpoint()
            .await
            .inbox
            .get(&key)
            .map(|record| (record.staged_sequence, record.staged_index));
        let message = outbound_record(draft, source_order);
        self.append(RuntimeEvent::QueueOutboundForInbox {
            key,
            message: message.clone(),
        })
        .await?;
        Ok(message)
    }

    pub(super) async fn set_outbound_state(
        &self,
        client_id: impl Into<String>,
        state: OutboundState,
    ) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::SetOutboundState {
            client_id: client_id.into(),
            state,
        })
        .await
    }

    #[cfg(test)]
    pub(super) async fn reserve_idempotency(
        &self,
        key: impl Into<String>,
    ) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::ReserveIdempotency { key: key.into() })
            .await
    }

    #[cfg(test)]
    pub(super) async fn set_idempotency_state(
        &self,
        key: impl Into<String>,
        state: IdempotencyState,
    ) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::SetIdempotencyState {
            key: key.into(),
            state,
        })
        .await
    }

    pub(super) async fn set_selection(
        &self,
        target_id: impl Into<String>,
    ) -> Result<RemoteSelection, RuntimeStoreError> {
        let selection = RemoteSelection {
            target_id: target_id.into(),
            selected_at_ms: unix_time_ms(),
        };
        self.append(RuntimeEvent::SetSelection {
            selection: Some(selection.clone()),
        })
        .await?;
        Ok(selection)
    }

    pub(super) async fn clear_selection(&self) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::SetSelection { selection: None })
            .await
    }

    pub(super) async fn set_list_context(
        &self,
        kind: RemoteListKind,
        page: u16,
        target_ids: Vec<String>,
    ) -> Result<RemoteListContext, RuntimeStoreError> {
        let context = RemoteListContext {
            kind,
            page,
            target_ids,
            listed_at_ms: unix_time_ms(),
        };
        self.append(RuntimeEvent::SetListContext {
            context: Some(context.clone()),
        })
        .await?;
        Ok(context)
    }

    pub(super) async fn clear_list_context(&self) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::SetListContext { context: None })
            .await
    }

    pub(super) async fn compact(&self) -> Result<(), RuntimeStoreError> {
        let inner = Arc::clone(&self.inner);
        tokio::spawn(async move { inner.compact().await })
            .await
            .map_err(|_| RuntimeStoreError::TaskJoin)?
    }

    pub(super) async fn clear(&self) -> Result<(), RuntimeStoreError> {
        self.append(RuntimeEvent::Reset).await?;
        self.compact().await
    }

    async fn append(&self, event: RuntimeEvent) -> Result<(), RuntimeStoreError> {
        let inner = Arc::clone(&self.inner);
        tokio::spawn(async move { inner.append(event).await })
            .await
            .map_err(|_| RuntimeStoreError::TaskJoin)?
    }

    #[cfg(test)]
    pub(super) fn directory_for_test(&self) -> &Path {
        &self.inner.directory
    }
}

impl RuntimeStoreInner {
    async fn append(&self, event: RuntimeEvent) -> Result<(), RuntimeStoreError> {
        if self.poisoned.load(Ordering::Acquire) {
            return Err(RuntimeStoreError::RecoveryRequired);
        }
        let mut current = self.state.lock().await;
        if self.poisoned.load(Ordering::Acquire) {
            return Err(RuntimeStoreError::RecoveryRequired);
        }
        let record = JournalRecord::new(current.next_sequence, event);
        let mut next = current.clone();
        next.apply(&record)?;
        storage::validate_snapshot_size(&next)?;
        let directory = self.directory.clone();
        let persisted_record = record.clone();
        let baseline = current.clone();
        let persisted = tokio::task::spawn_blocking(move || {
            match storage::append_record(&directory, &persisted_record) {
                Err(RuntimeStoreError::JournalFull) => {
                    storage::compact_runtime(&directory, &baseline)?;
                    storage::append_record(&directory, &persisted_record)
                }
                result => result,
            }
        })
        .await;
        let persisted = match persisted {
            Ok(result) => result,
            Err(_) => {
                self.poisoned.store(true, Ordering::Release);
                return Err(RuntimeStoreError::TaskJoin);
            }
        };
        if let Err(error) = persisted {
            if error.requires_reopen() {
                self.poisoned.store(true, Ordering::Release);
            }
            return Err(error);
        }
        *current = next;
        Ok(())
    }

    async fn compact(&self) -> Result<(), RuntimeStoreError> {
        if self.poisoned.load(Ordering::Acquire) {
            return Err(RuntimeStoreError::RecoveryRequired);
        }
        let current = self.state.lock().await;
        if self.poisoned.load(Ordering::Acquire) {
            return Err(RuntimeStoreError::RecoveryRequired);
        }
        let snapshot = current.clone();
        let directory = self.directory.clone();
        let compacted =
            tokio::task::spawn_blocking(move || storage::compact_runtime(&directory, &snapshot))
                .await;
        match compacted {
            Ok(Ok(())) => Ok(()),
            Ok(Err(error)) => {
                if error.requires_reopen() {
                    self.poisoned.store(true, Ordering::Release);
                }
                Err(error)
            }
            Err(_) => {
                self.poisoned.store(true, Ordering::Release);
                Err(RuntimeStoreError::TaskJoin)
            }
        }
    }
}

#[derive(Clone)]
pub(super) struct RuntimeCheckpoint {
    pub(super) cursor: Option<SecretValue>,
    pub(super) inbox: BTreeMap<String, InboxRecord>,
    pub(super) outbox: BTreeMap<String, OutboundRecord>,
    pub(super) idempotency: BTreeMap<String, IdempotencyState>,
    pub(super) selection: Option<RemoteSelection>,
    pub(super) list_context: Option<RemoteListContext>,
}

impl RuntimeCheckpoint {
    fn from_state(state: &RuntimeState) -> Self {
        Self {
            cursor: state.cursor.clone(),
            inbox: state.inbox.clone(),
            outbox: state.outbox.clone(),
            idempotency: state.idempotency.clone(),
            selection: state.selection.clone(),
            list_context: state.list_context.clone(),
        }
    }
}

impl fmt::Debug for RuntimeCheckpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RuntimeCheckpoint")
            .field("has_cursor", &self.cursor.is_some())
            .field("inbox_count", &self.inbox.len())
            .field("outbox_count", &self.outbox.len())
            .field("idempotency_count", &self.idempotency.len())
            .field("has_selection", &self.selection.is_some())
            .field("has_list_context", &self.list_context.is_some())
            .finish()
    }
}

fn random_client_id() -> String {
    format!("a3s-{:032x}", rand::random::<u128>())
}

fn outbound_record(draft: OutboundDraft, source_order: Option<(u64, u16)>) -> OutboundRecord {
    let (source_inbox_sequence, source_inbox_index) = source_order
        .map(|(sequence, index)| (Some(sequence), Some(index)))
        .unwrap_or((None, None));
    OutboundRecord {
        client_id: random_client_id(),
        recipient_id: draft.recipient_id,
        context_token: draft.context_token,
        text: draft.text,
        run_id: draft.run_id,
        source_inbox_sequence,
        source_inbox_index,
        created_at_ms: unix_time_ms(),
        state: OutboundState::Pending,
    }
}

fn unix_time_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .try_into()
        .unwrap_or(u64::MAX)
}

#[derive(Debug, Error)]
pub(super) enum RuntimeStoreError {
    #[error("Weixin runtime storage path is unsafe")]
    UnsafePath,
    #[error("another A3S runtime already owns the Weixin account lock")]
    LockContended,
    #[error("Weixin runtime recovery is required")]
    RecoveryRequired,
    #[error("Weixin runtime state is corrupt")]
    CorruptState,
    #[error("Weixin runtime file exceeds its size limit")]
    FileTooLarge,
    #[error("Weixin runtime journal record exceeds its size limit")]
    RecordTooLarge,
    #[error("Weixin runtime journal requires compaction")]
    JournalFull,
    #[error("Weixin runtime snapshot exceeds its size limit")]
    SnapshotTooLarge,
    #[error("Weixin private storage validation failed")]
    PrivateStorage(#[from] CredentialStoreError),
    #[error("Weixin runtime model validation failed")]
    Model(#[from] RuntimeModelError),
    #[error("Weixin runtime serialization failed")]
    Serialization(#[from] serde_json::Error),
    #[error("Weixin runtime storage I/O failed")]
    Io(#[source] std::io::Error),
    #[error("Weixin runtime storage task failed")]
    TaskJoin,
}

impl RuntimeStoreError {
    fn requires_reopen(&self) -> bool {
        matches!(
            self,
            Self::RecoveryRequired
                | Self::CorruptState
                | Self::PrivateStorage(_)
                | Self::Io(_)
                | Self::TaskJoin
        )
    }
}