a3s 0.8.1

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
//! Shared application messages, rebuild state, and asynchronous runtime types.

use super::*;

/// Shared, single-consumer receiver for the active agent run. Wrapped so the
/// pump command can own a clone; pumps run sequentially, so the mutex never
/// actually contends.
pub(super) type SharedRx = Arc<Mutex<mpsc::Receiver<AgentEvent>>>;
pub(super) type SharedManifestRx =
    Arc<Mutex<tokio::sync::broadcast::Receiver<LocalWorkspaceManifestSnapshot>>>;
pub(super) type SharedActiveSession = Arc<std::sync::Mutex<Arc<AgentSession>>>;
pub(super) type StreamJoin = tokio::task::JoinHandle<()>;
pub(super) type HostToolAbort = tokio::task::AbortHandle;

#[derive(Clone, Copy, PartialEq)]
pub(super) enum State {
    Idle,
    Streaming,
    Awaiting,
    Rebuilding,
}

#[derive(Clone, Copy, Debug)]
pub(super) enum ViewportAnchor {
    Bottom,
    Transcript(TranscriptAnchor),
    Absolute(usize),
}

#[derive(Clone)]
#[allow(clippy::enum_variant_names)]
pub(super) enum Action {
    ScrollUp,
    ScrollDown,
    ScrollTop,
    ScrollBottom,
}

/// Set by `/update` when an upgrade is available: after the TUI exits (terminal
/// restored), `run` performs the upgrade (Homebrew or standalone download) and
/// re-execs the freshly-installed binary.
pub(super) static UPGRADE_ON_EXIT: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);
/// The latest version tag, stashed by `/update` for the post-exit upgrade.
pub(super) static LATEST: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct AutoReviewKey {
    pub(super) session_id: String,
    pub(super) revision: u64,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct AutoReviewTicket {
    pub(super) id: u64,
    pub(super) key: AutoReviewKey,
}

#[derive(Debug)]
pub(super) struct AutoReviewTracker {
    pub(super) revision: u64,
    pub(super) reviewed: Option<AutoReviewKey>,
    pub(super) inflight: Option<AutoReviewTicket>,
    pub(super) next_ticket_id: u64,
}

impl AutoReviewTracker {
    pub(super) fn new(revision: u64) -> Self {
        Self {
            revision,
            reviewed: None,
            inflight: None,
            next_ticket_id: 0,
        }
    }

    pub(super) fn on_user_turn(&mut self) {
        self.revision = self.revision.wrapping_add(1);
    }

    pub(super) fn current_key(&self, session_id: &str) -> AutoReviewKey {
        AutoReviewKey {
            session_id: session_id.to_string(),
            revision: self.revision,
        }
    }

    pub(super) fn current_is_reviewed(&self, session_id: &str) -> bool {
        self.reviewed
            .as_ref()
            .is_some_and(|key| key.session_id == session_id && key.revision == self.revision)
    }

    /// Mark the current conversation revision as considered and, when it has a
    /// real user turn, issue a unique ticket for the asynchronous review.
    pub(super) fn begin(
        &mut self,
        session_id: &str,
        has_user_turn: bool,
    ) -> Option<AutoReviewTicket> {
        let key = self.current_key(session_id);
        if self.reviewed.as_ref() == Some(&key) {
            return None;
        }
        self.reviewed = Some(key.clone());
        if !has_user_turn {
            return None;
        }

        self.next_ticket_id = self.next_ticket_id.wrapping_add(1);
        let ticket = AutoReviewTicket {
            id: self.next_ticket_id,
            key,
        };
        // A newer conversation may replace an older in-flight ticket. The old
        // result will fail the exact-ticket check in `accept` and cannot clear it.
        self.inflight = Some(ticket.clone());
        Some(ticket)
    }

    pub(super) fn accept(&mut self, ticket: &AutoReviewTicket, session_id: &str) -> bool {
        if self.inflight.as_ref() != Some(ticket) {
            return false;
        }
        self.inflight = None;
        ticket.key.session_id == session_id
            && ticket.key.revision == self.revision
            && self.reviewed.as_ref() == Some(&ticket.key)
    }
}

pub(super) fn auto_review_history_has_user_turn(history: &[Message]) -> bool {
    history
        .iter()
        .any(|message| message.role == "user" && !message.text().trim().is_empty())
}

pub(super) enum SessionRebuildAction {
    Model {
        model: String,
        source: ModelSelectionSource,
        llm_override: Option<LlmOverride>,
        context_limit: u32,
    },
    Effort {
        selected: usize,
        codex_effort: Option<CodexEffortStatus>,
    },
    GoalStart {
        generation: u64,
        previous_effort: usize,
        previous_goal: Option<String>,
        previous_goal_since: Option<Instant>,
    },
    GoalRestore,
    Compact {
        summary: String,
        session_id: String,
    },
    Fork {
        session_id: String,
    },
    Clear {
        session_id: String,
    },
    Reload {
        skill_count: usize,
    },
    Refresh {
        failure_context: Option<&'static str>,
    },
}

pub(super) struct SessionRebuildProfile {
    pub(super) session_id: String,
    pub(super) model: Option<String>,
    pub(super) effort: usize,
    pub(super) context_limit: u32,
    pub(super) llm_override: Option<LlmOverride>,
    pub(super) compact_summary: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SessionRebuildMode {
    /// Reconfigure an existing persisted session without ever replacing a
    /// failed resume with an empty session using the same id.
    ResumeExisting,
    /// Materialize a deliberately new id for `/clear` or `/compact`.
    CreateFresh,
}

pub(super) enum Msg {
    Term(Event),
    // Boxed: AgentEvent is large; keeps the Msg enum small.
    Agent {
        source: SharedRx,
        event: Box<AgentEvent>,
    },
    Submit(String),
    StreamStarted {
        token: u64,
        session: Arc<AgentSession>,
        rx: SharedRx,
        join: StreamJoin,
    },
    StreamEnded(SharedRx),
    StreamJoinSettled {
        token: u64,
        synthesis: Option<(String, String)>,
    },
    DiscardedStreamSettled,
    /// Session cancellation and the active stream worker have settled enough
    /// for the terminal program to restore the shell without detaching work.
    QuitReady,
    StreamError {
        token: u64,
        error: String,
    },
    WorkspaceManifest(Box<LocalWorkspaceManifestSnapshot>),
    WorkspaceManifestStopped,
    SpinnerTick,
    /// Advance Codex-style Markdown commit animation independently from the
    /// slower status spinner.
    StreamCommitTick,
    /// Advance the welcome-mascot animation frame.
    BannerTick,
    /// Drive the short, high-frame-rate Ultracode activation transition.
    UltracodeTick {
        epoch: u64,
    },
    ModalConfirm {
        tool_id: String,
        approved: bool,
        approve_all_pending: bool,
    },
    BackgroundSubagentFinished {
        session_id: String,
        generation: u64,
        task_id: String,
        agent: String,
        output: String,
        outcome: SubagentOutcome,
        finished_ms: u64,
    },
    BackgroundSubagentWatchStopped {
        session_id: String,
        generation: u64,
        task_id: String,
    },
    SubagentSnapshots {
        session_id: String,
        generation: u64,
        request_id: u64,
        snapshots: Vec<RestoredSubagentSnapshot>,
    },
    /// The active DeepResearch parent reached a report terminal state. Its
    /// children must be terminal before the report view opens and autonomy is
    /// restored, otherwise the footer advertises work after the parent ended.
    DeepResearchSubagentsSettled {
        session_id: String,
        generation: u64,
        exit: DeepResearchSettlementExit,
        settlements: Vec<DeepResearchSubagentSettlement>,
    },
    DeepResearchJournalFinalized {
        run_id: String,
        exit: DeepResearchSettlementExit,
        result: Result<ResearchRunProjection, String>,
    },
    DeepResearchJournalEventRecorded {
        run_id: String,
        result: Result<ResearchRunProjection, String>,
    },
    Resume,
    Interrupted {
        goal_cancelled: bool,
        status_entry: TranscriptEntryId,
    },
    /// Output of a `!`-prefixed shell command.
    ShellOutput(String),
    ResearchDiagnostic(Result<String, String>),
    /// Host-controlled `?` deep-research workflow finished; next step is synthesis.
    DeepResearchWorkflowCompleted {
        query: String,
        os_runtime: bool,
        args: serde_json::Value,
        result: Result<ToolCallResult, String>,
        convergence: ConvergenceDecision,
        accepted_evidence: Vec<AcceptedEvidence>,
    },
    /// A DeepResearch synthesis/repair stream exceeded its host-side model budget.
    DeepResearchSynthesisTimedOut {
        token: u64,
    },
    /// A timed-out DeepResearch synthesis/repair stream was cancelled at the session layer.
    DeepResearchSynthesisTimedOutAfterCancel {
        token: u64,
        status: String,
        streamed_text: String,
        report_completed: bool,
    },
    /// `/update` version check finished: the latest version tag, if reachable.
    UpdatePlan(Option<String>),
    /// `/update` found no binary upgrade was needed and repaired companion tools.
    UpdateRepair {
        status_entry: TranscriptEntryId,
        result: Result<Vec<String>, String>,
    },
    /// OS login completed.
    OsLogin {
        status_entry: TranscriptEntryId,
        result: Result<String, String>,
    },
    /// Post-login SSH-key sync finished (registers the local pubkey with OS).
    SshKeySynced(crate::a3s_os::SshKeyOutcome),
    /// OS access token was refreshed (or refresh failed) in the background.
    OsRefreshed(Result<crate::a3s_os::StoredOsSession, String>),
    /// OS unified-gateway model ids fetched for the `/model` picker.
    OsGatewayModels {
        login_at_ms: u64,
        result: Result<Vec<crate::a3s_os::GatewayModel>, String>,
    },
    /// Models discovered from a detected local developer-tool account.
    AccountModels {
        provider: crate::account_providers::AccountProvider,
        result: Result<Vec<String>, String>,
    },
    /// Host-owned continuation for an active `/goal`. The generation makes a
    /// delayed retry inert after Esc, `/goal clear`, or a replacement goal.
    GoalContinue {
        generation: u64,
        prompt: String,
    },
    /// A streaming `/goal clear` finished cancelling and joining the old run.
    GoalCleared,
    /// Picker-visible models refreshed through the signed-in Codex CLI.
    CodexModels(Result<Vec<crate::account_providers::codex::CodexModel>, String>),
    /// An async session rebuild for `/model`, `/effort`, or another
    /// session-mutating TUI action completed.
    SessionRebuilt {
        request_id: u64,
        action: SessionRebuildAction,
        result: Box<panels::model::SessionRebuildResult>,
    },
    /// `/fork` copied the session under a new id (Ok) — swap the active session to
    /// it — or failed (Err with a reason).
    Forked {
        request_id: u64,
        result: Result<String, String>,
    },
    /// `/memory` graph data loaded (timeline + details + derived graph).
    MemoryLoaded(MemPanelData),
    /// A `/memory` forget-candidate deletion finished, with fresh graph data.
    MemoryForgotten(Result<(String, MemPanelData), String>),
    /// Asset-scoped OS asset list loaded.
    AssetListLoaded(Result<panels::asset_resources::AssetListFetch, String>),
    /// Runtime activity rows loaded for an asset-scoped activity panel.
    RuntimeActivityLoaded(Result<panels::asset_resources::RuntimeActivityFetch, String>),
    /// `/kb import` finished; carries the one-line summary to show.
    KbAdded(String),
    /// `/ctx <query>` finished: raw `ctx search --json` stdout (or the error).
    CtxResults {
        status_entry: TranscriptEntryId,
        result: Result<String, String>,
    },
    /// `/ctx <n>` finished: (hit title, transcript window) to stage as context.
    CtxWindow {
        status_entry: TranscriptEntryId,
        result: Result<(String, String), String>,
    },
    /// `/ctx save <n>` finished: Ok(hit title) once written to the memory store.
    CtxSaved(Result<String, String>),
    /// `/sleep` finished persisting its consolidated memories (count on Ok).
    SleepSaved(Result<usize, String>),
    /// `/flow` published/opened/inspected an OS Workflow as a Service asset.
    FlowOsCompleted {
        status_entry: TranscriptEntryId,
        result: Result<panels::flow::FlowOsResult, String>,
    },
    /// `/agent` published/opened an OS agent asset through Agent as a Service or Function as a Service.
    AgentOsCompleted {
        status_entry: TranscriptEntryId,
        result: Result<panels::agent::AgentOsResult, String>,
    },
    /// `/mcp` published/ran/tested an OS Function as a Service MCP asset.
    McpOsCompleted {
        status_entry: TranscriptEntryId,
        result: Result<panels::mcp::McpOsResult, String>,
    },
    /// `/skill` published/deployed/inspected an OS Function as a Service skill asset.
    SkillOsCompleted {
        status_entry: TranscriptEntryId,
        result: Result<panels::skill::SkillOsResult, String>,
    },
    /// `/okf` published/deployed an OS Knowledge service package asset.
    OkfOsCompleted {
        status_entry: TranscriptEntryId,
        result: Result<panels::okf::OkfOsResult, String>,
    },
    /// Asset source was cloned into the local asset workspace.
    AssetCloned {
        status_entry: TranscriptEntryId,
        result: Result<asset_clone::AssetCloneResult, String>,
    },
    /// `/memory` → ctx back-jump finished: (ctx event id, transcript window).
    CtxMemorySource(Result<(String, String), String>),
    /// Inactivity auto-review summary text, tagged so stale background results
    /// cannot appear after a new turn, `/clear`, compact, or fork.
    AutoReview {
        ticket: AutoReviewTicket,
        text: String,
    },
    /// `/compact` completed its direct, tool-free summary request.
    Compacted(Result<Option<String>, String>),
    /// Startup update check completed with the latest published version (if any).
    UpdateCheck(Option<String>),
}

pub(super) struct RestoredSubagentSnapshot {
    pub(super) snapshot: a3s_code_core::SubagentTaskSnapshot,
    pub(super) parent_result_expected: bool,
}

pub(super) struct DeepResearchSubagentSettlement {
    pub(super) task_id: String,
    pub(super) agent: String,
    pub(super) output: String,
    pub(super) outcome: SubagentOutcome,
    pub(super) finished_ms: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum DeepResearchSettlementExit {
    ReportReady,
    Interrupted,
}

impl DeepResearchSettlementExit {
    pub(super) fn opens_report(self) -> bool {
        matches!(self, Self::ReportReady)
    }
}

impl From<Event> for Msg {
    fn from(event: Event) -> Self {
        // Ctrl+C is handled in the key loop as a global graceful quit key.
        Msg::Term(event)
    }
}