saya-cli 0.4.1

Database-aware AI agent for the terminal: full-screen TUI, schema discovery, and bounded read-only SQL over PostgreSQL, MySQL, SQLite, DuckDB, and Snowflake.
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
use saya_agent::{
    KnowledgeOutcome, LearningSkipReason, OverrideFindingDto, ProposedClaimDto,
    SuppliedContractDto, TokenUsage, ToolEffect, UsageCall, read_only_permits,
};
use saya_config::OutputFormat;
use saya_types::{QueryResult, SchemaTree};
use serde::Serialize;
mod contract_view;
mod io_view;
mod render_contract;
mod render_delta;
mod render_io;
mod render_json;
mod render_learned;
mod render_memory;
/// The shared tool-call grouper and shaper both adapters consume: the piped
/// text renderer buffers through it, the TUI transcript follows in slice 3.
pub(crate) mod tool_groups;
pub use contract_view::{
    ContractClaimView, ContractConflictView, ContractQueueItemView, ContractView,
};
pub use io_view::{ContractExportView, ContractImportClaimView, ContractImportView};
/// Re-exported for the TUI, which renders [`AgentEvent::KnowledgeProposed`] in
/// `apply_event` and shares this shaper so the wording lives in one place.
pub(crate) use render_learned::knowledge_learned_text;
/// Re-exported for the TUI, which renders [`AgentEvent::KnowledgeOverridden`] in
/// `apply_event` and shares this shaper so the wording lives in one place (A1).
pub(crate) use render_memory::knowledge_overridden_text;
/// Re-exported for the TUI, which renders [`AgentEvent::KnowledgeSupplied`] in
/// `apply_event` and shares this shaper so the wording lives in one place.
pub(crate) use render_memory::knowledge_supplied_text;
/// Re-exported for the TUI, which renders [`AgentEvent::KnowledgeLearningDisabled`]
/// in `apply_event` and shares this shaper so the wording lives in one place.
pub(crate) use render_memory::learning_disabled_text;
/// Re-exported for the TUI, which renders [`AgentEvent::KnowledgeLearningSkipped`]
/// in `apply_event` and shares this shaper so the wording lives in one place
/// (packet-54).
pub(crate) use render_memory::learning_skipped_text;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderFormat {
    Text,
    Json,
    Ndjson,
}
impl From<crate::cli::FormatArg> for RenderFormat {
    fn from(value: crate::cli::FormatArg) -> Self {
        match value {
            crate::cli::FormatArg::Text => Self::Text,
            crate::cli::FormatArg::Json => Self::Json,
            crate::cli::FormatArg::Ndjson => Self::Ndjson,
        }
    }
}
impl From<OutputFormat> for RenderFormat {
    fn from(value: OutputFormat) -> Self {
        match value {
            OutputFormat::Text => Self::Text,
            OutputFormat::Json => Self::Json,
            OutputFormat::Ndjson => Self::Ndjson,
        }
    }
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum TerminalEvent {
    AssistantText {
        text: String,
    },
    ToolRequested {
        name: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
        /// The tool's **declared effect**, carried from the event the loop
        /// emitted so the text line's effect claim is derived from the same
        /// declaration the approval gate reads — never from the tool's name.
        /// Absent only when no declaration exists (an unknown tool, which
        /// cannot run), and skipped on the wire then, so a stream that never
        /// declared a tool keeps the shape it always had.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        effect: Option<ToolEffect>,
    },
    ToolCompleted {
        name: String,
        summary: String,
    },
    ToolDenied {
        name: String,
        reason: String,
    },
    /// What memory **supplied** to the turn, emitted once before the provider
    /// call. Carries the outcome, the supplied contracts (claim DTOs,
    /// no opaque identity), and the count the bounds dropped. Text is shaped in
    /// [`render_memory`]; JSON/NDJSON fall out of the serde derive.
    KnowledgeSupplied {
        outcome: KnowledgeOutcome,
        contracts: Vec<SuppliedContractDto>,
        dropped_by_bounds: usize,
    },
    /// One fact SAYA came away from the turn knowing (`AgentEvent::KnowledgeProposed`).
    /// Emitted once per learned claim, after the answer. Text is shaped in
    /// [`render_learned`] and carries no claim id — learning is not something the
    /// user asked for, so it must not hand them a hash to manage. JSON/NDJSON keep
    /// the DTO whole, id included, for machine consumers.
    KnowledgeLearned {
        claim: ProposedClaimDto,
    },
    /// A confirmed claim the turn's SQL **contradicted**. Emitted at
    /// most once per turn, after the loop, carrying every finding the detector
    /// raised. The finding says the SQL **referenced** columns, never that it
    /// **used** them — the extractor cannot prove role. Text is shaped in
    /// [`render_memory`]; JSON/NDJSON fall out of the serde derive.
    KnowledgeOverridden {
        findings: Vec<OverrideFindingDto>,
    },
    /// Post-turn extraction was skipped after the turn succeeded — no memory
    /// was recorded, and the line says so. Trails the answer.
    /// Text is shaped in [`render_memory`]; JSON/NDJSON fall out of the serde
    /// derive.
    KnowledgeLearningSkipped {
        reason: LearningSkipReason,
    },
    /// The extraction circuit breaker tripped this turn — no more extraction
    /// requests this session (`AgentEvent::KnowledgeLearningDisabled`).
    /// Trails the answer, after `KnowledgeLearningSkipped`. Text is shaped
    /// in [`render_memory`]; JSON/NDJSON fall out of the serde derive.
    KnowledgeLearningDisabled {
        model: String,
        misses: u32,
    },
    Complete,
    /// The provider stream failed mid-answer and the turn is being retried
    /// (`AgentEvent::TurnReset`). The partial answer printed so far is
    /// discarded; the retry re-streams the full answer. Carried on the
    /// JSON/NDJSON stream under its own tag so a machine consumer can replace
    /// the text it accumulated instead of appending; the text adapter prints a
    /// one-line notice, because an answer that silently restarts mid-stream
    /// would read as the model repeating itself.
    TurnReset,
    /// The SQL the model designated as the answering query for the turn.
    /// Carried on the NDJSON stream so a harness can pair the answer with its
    /// query; silent in the text adapter, where the SQL was already shown when
    /// the query ran.
    AnswerDesignated {
        sql: String,
    },
    /// The consensus decision over multiple candidate attempts — emitted once,
    /// after all attempts, whenever more than one attempt ran. Carries the
    /// winning SQL (or `None` when the attempts disagreed with no tie-break)
    /// and the vote tallies. Text is shaped inline; JSON/NDJSON fall out of the
    /// serde derive.
    ConsensusDecided {
        sql: Option<String>,
        attempts: usize,
        voted: usize,
        votes: usize,
        margin: usize,
        tied: bool,
        probe_broke_tie: bool,
    },
    /// The token counts one provider call reported (`AgentEvent::Usage`),
    /// named by `call` so a consumer can keep the answering rounds' cost apart
    /// from the extraction call's. Carried on the JSON/NDJSON stream for
    /// machine consumers; the text adapter renders nothing, because the
    /// interactive surfaces for it already exist (the per-turn token line and
    /// `/usage`) and a pipe's reader has the answer above it.
    Usage {
        call: UsageCall,
        usage: TokenUsage,
    },
    Result {
        message: String,
    },
    QueryResult {
        result: QueryResult,
    },
    Schema {
        schema: SchemaTree,
    },
    NotImplemented {
        feature: String,
    },
    Diagnostic {
        message: String,
    },
    Error {
        message: String,
    },
    ContractList {
        contracts: Vec<ContractView>,
    },
    ContractShow {
        contract: ContractView,
    },
    ContractChanged {
        claim_id: String,
        action: String,
        status: String,
    },
    ContractRemembered {
        /// Carried for machine consumers only. The text renderer never prints
        /// it: a 64-character hash is the system's business, and a script that
        /// remembers then forgets still needs a handle without a second call.
        claim_id: String,
        object: String,
        kind: String,
        value: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        column: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        previous: Option<String>,
        action: String,
        status: String,
    },
    ContractQueue {
        items: Vec<ContractQueueItemView>,
    },
    ContractImport {
        report: ContractImportView,
    },
    ContractExport {
        report: ContractExportView,
    },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rendered {
    pub stdout: String,
    pub stderr: String,
}

pub fn render_event(event: &TerminalEvent, format: RenderFormat) -> Rendered {
    match format {
        RenderFormat::Text => text_event(event),
        RenderFormat::Json | RenderFormat::Ndjson => render_json::render(event),
    }
}

pub(crate) fn sanitize_terminal(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\n' | '\t' => out.push(c),
            '\x00'..='\x1F' | '\x7F' | '\u{0080}'..='\u{009F}' => {}
            _ => out.push(c),
        }
    }
    out
}

/// Shapes the `ToolRequested` line: the one a pipe reader sees *before* a tool
/// runs, naming what the call may do to their machine. The `read-only` claim
/// is derived from the tool's **declared effect** through
/// [`read_only_permits`] — the same predicate the approval policy gates on —
/// so the line and the gate cannot drift: a workspace-write tool (including
/// `scratch_sql`, which declares the same effect), a network-reaching tool,
/// or any future effect that fails the predicate is never announced as
/// read-only.
///
/// The other half of the wording is a deliberate non-claim: when the
/// declaration does not prove read-only, the line says only "Using tool".
/// A positive per-effect label ("writing the workspace", "network access")
/// would need a match over the effect variants kept current by hand, and its
/// default arm would be exactly the defect this fixes — a new variant silently
/// rendering under the wrong claim. "Read-only" is the one claim the declared
/// effect proves cheaply, and only that one is made; the detail line (the SQL,
/// the path) and the tool's name carry what the call actually does.
fn tool_requested_text(name: &str, detail: Option<&str>, effect: Option<&ToolEffect>) -> String {
    let head = if effect.is_some_and(read_only_permits) {
        format!("Using read-only tool: {name}\n")
    } else {
        format!("Using tool: {name}\n")
    };
    match detail {
        Some(detail) => format!("{head}  {detail}\n"),
        None => head,
    }
}

fn text_event(event: &TerminalEvent) -> Rendered {
    let rendered = match event {
        TerminalEvent::Diagnostic { message } | TerminalEvent::Error { message } => Rendered {
            stdout: String::new(),
            stderr: format!("{message}\n"),
        },
        TerminalEvent::AssistantText { text } => render_delta::text(text),
        TerminalEvent::ToolRequested {
            name,
            detail,
            effect,
        } => Rendered {
            stdout: tool_requested_text(name, detail.as_deref(), effect.as_ref()),
            stderr: String::new(),
        },
        TerminalEvent::ToolCompleted { name, summary } => Rendered {
            stdout: format!("{name}: {summary}\n"),
            stderr: String::new(),
        },
        TerminalEvent::ToolDenied { name, reason } => Rendered {
            stdout: format!("Approval denied for {name}: {reason}\n"),
            stderr: String::new(),
        },
        TerminalEvent::KnowledgeSupplied {
            outcome,
            contracts,
            dropped_by_bounds,
        } => Rendered {
            stdout: render_memory::knowledge_supplied_text(*outcome, contracts, *dropped_by_bounds),
            stderr: String::new(),
        },
        TerminalEvent::KnowledgeLearned { claim } => Rendered {
            stdout: render_learned::knowledge_learned_text(claim),
            stderr: String::new(),
        },
        TerminalEvent::KnowledgeOverridden { findings } => Rendered {
            stdout: render_memory::knowledge_overridden_text(findings),
            stderr: String::new(),
        },
        TerminalEvent::KnowledgeLearningSkipped { reason } => Rendered {
            stdout: render_memory::learning_skipped_text(*reason),
            stderr: String::new(),
        },
        TerminalEvent::KnowledgeLearningDisabled { model, misses } => Rendered {
            stdout: render_memory::learning_disabled_text(model, *misses),
            stderr: String::new(),
        },
        TerminalEvent::Complete => Rendered {
            stdout: "\n".into(),
            stderr: String::new(),
        },
        TerminalEvent::TurnReset => Rendered {
            stdout: "provider stream interrupted — retrying\n".into(),
            stderr: String::new(),
        },
        TerminalEvent::AnswerDesignated { .. } => Rendered {
            stdout: String::new(),
            stderr: String::new(),
        },
        TerminalEvent::ConsensusDecided {
            sql,
            attempts,
            voted,
            votes,
            margin: _,
            tied,
            probe_broke_tie,
        } => Rendered {
            stdout: consensus_text(
                sql.as_deref(),
                *attempts,
                *voted,
                *votes,
                *tied,
                *probe_broke_tie,
            ),
            stderr: String::new(),
        },
        TerminalEvent::Usage { .. } => Rendered {
            stdout: String::new(),
            stderr: String::new(),
        },
        TerminalEvent::Result { message } => Rendered {
            stdout: format!("{message}\n"),
            stderr: String::new(),
        },
        TerminalEvent::QueryResult { result } => Rendered {
            stdout: query_text(result),
            stderr: String::new(),
        },
        TerminalEvent::Schema { schema } => Rendered {
            stdout: format!("{}\n", schema_text(schema)),
            stderr: String::new(),
        },
        TerminalEvent::NotImplemented { feature } => Rendered {
            stdout: format!("Not implemented: {feature}\n"),
            stderr: String::new(),
        },
        TerminalEvent::ContractList { contracts } => render_contract::list(contracts),
        TerminalEvent::ContractShow { contract } => render_contract::show(contract),
        TerminalEvent::ContractChanged {
            claim_id,
            action,
            status,
        } => render_contract::changed(claim_id, action, status),
        TerminalEvent::ContractRemembered {
            claim_id: _,
            object,
            kind,
            value,
            column,
            previous,
            action,
            status,
        } => render_contract::remembered(
            object,
            kind,
            value,
            column.as_deref(),
            previous.as_deref(),
            action,
            status,
        ),
        TerminalEvent::ContractQueue { items } => render_contract::queue(items),
        TerminalEvent::ContractImport { report } => render_io::import(report),
        TerminalEvent::ContractExport { report } => render_io::export(report),
    };
    Rendered {
        stdout: sanitize_terminal(&rendered.stdout),
        stderr: sanitize_terminal(&rendered.stderr),
    }
}

fn query_text(result: &QueryResult) -> String {
    let mut output = result.columns.join("\t");
    if !output.is_empty() {
        output.push('\n');
    }
    for row in &result.rows {
        let value = match row {
            serde_json::Value::Array(values) => values
                .iter()
                .map(display_value)
                .collect::<Vec<_>>()
                .join("\t"),
            value => display_value(value),
        };
        output.push_str(&value);
        output.push('\n');
    }
    if result.truncated {
        output.push_str("[truncated]\n");
    }
    output
}

fn display_value(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(value) => value.clone(),
        value => value.to_string(),
    }
}

/// Shapes the `ConsensusDecided` line: how many attempts ran, how many voted,
/// and — when there is a winner — which SQL is believed. The line trails the
/// answer, naming the picked query so a reader knows which attempt's prose to
/// trust. No result rows; SQL text only, like `AnswerDesignated`.
fn consensus_text(
    sql: Option<&str>,
    attempts: usize,
    voted: usize,
    votes: usize,
    tied: bool,
    probe_broke_tie: bool,
) -> String {
    let head = format!("consensus · {attempts} attempts, {voted} voted, {votes} agreed");
    match sql {
        Some(sql) => {
            let how = if probe_broke_tie {
                "tie broken by evidence"
            } else {
                "agreed"
            };
            format!("{head} · {how}, believing: {sql}\n")
        }
        None if tied => format!("{head} · tied, no winner\n"),
        None => format!("{head} · no winner\n"),
    }
}

fn schema_text(schema: &SchemaTree) -> String {
    schema
        .databases
        .iter()
        .flat_map(|database| {
            database.schemas.iter().flat_map(move |schema| {
                schema
                    .tables
                    .iter()
                    .map(move |table| format!("{}.{}.{}", database.name, schema.name, table.name))
            })
        })
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sanitize_terminal_strips_control_bytes_and_preserves_tabs_and_newlines() {
        let input = "hello\x1b[31mRED\x1b[0m\tworld\n\x1b]0;pwned\x07\r\x7f\u{0080}\u{009f}";
        let sanitized = sanitize_terminal(input);
        assert_eq!(sanitized, "hello[31mRED[0m\tworld\n]0;pwned");
        assert!(!sanitized.contains('\x1b'));
        assert!(!sanitized.contains('\x07'));
        assert!(!sanitized.contains('\r'));
        assert!(!sanitized.contains('\x7f'));
        assert!(!sanitized.contains('\u{0080}'));
        assert!(!sanitized.contains('\u{009f}'));
    }

    #[test]
    fn test_text_render_sanitizes_terminal_control_sequences() {
        let raw_text = "col1\x1b[31mRED\x1b[0m\tcol2\x1b]0;pwned\x07";
        let event = TerminalEvent::QueryResult {
            result: QueryResult {
                columns: vec!["col1".into(), "col2".into()],
                rows: vec![serde_json::json!([raw_text, "ok"])],
                row_count: 1,
                truncated: false,
                executed_sql: "SELECT 1".into(),
            },
        };

        let rendered_text = render_event(&event, RenderFormat::Text);
        assert!(!rendered_text.stdout.contains('\x1b'));
        assert!(!rendered_text.stdout.contains('\x07'));
        assert!(rendered_text.stdout.contains("col1[31mRED[0m"));
        assert!(rendered_text.stdout.contains("pwned"));
        assert!(rendered_text.stdout.contains('\t'));
        assert!(rendered_text.stdout.contains('\n'));

        let rendered_json = render_event(&event, RenderFormat::Json);
        assert!(rendered_json.stdout.contains("\\u001b[31mRED\\u001b[0m"));
        assert!(rendered_json.stdout.contains("\\u001b]0;pwned\\u0007"));
    }

    #[test]
    fn test_assistant_text_and_delta_sanitizes_control_sequences() {
        let raw = "\x1b[31mRED\x1b[0m\x1b]0;pwned\x07";
        let delta_rendered = render_delta::text(raw);
        assert!(!delta_rendered.stdout.contains('\x1b'));
        assert!(!delta_rendered.stdout.contains('\x07'));
        assert_eq!(delta_rendered.stdout, "[31mRED[0m]0;pwned");

        let event = TerminalEvent::AssistantText {
            text: raw.to_string(),
        };
        let text_rendered = render_event(&event, RenderFormat::Text);
        assert!(!text_rendered.stdout.contains('\x1b'));
        assert!(!text_rendered.stdout.contains('\x07'));

        let json_rendered = render_event(&event, RenderFormat::Json);
        assert!(json_rendered.stdout.contains("\\u001b"));
    }

    #[test]
    fn test_contract_remembered_replaced_render() {
        let event = TerminalEvent::ContractRemembered {
            claim_id: "ki-123".to_string(),
            object: "pagila.public.rental".to_string(),
            kind: "grain".to_string(),
            value: "one row per rental per day".to_string(),
            column: None,
            previous: Some("one row per rental".to_string()),
            action: "replaced".to_string(),
            status: "confirmed".to_string(),
        };
        let text_rendered = render_event(&event, RenderFormat::Text);
        assert_eq!(
            text_rendered.stdout,
            "replaced grain for pagila.public.rental: \"one row per rental\" -> \"one row per rental per day\"\n"
        );

        let event_col = TerminalEvent::ContractRemembered {
            claim_id: "ki-456".to_string(),
            object: "pagila.public.rental".to_string(),
            kind: "column-role".to_string(),
            value: "event_time".to_string(),
            column: Some("rental_date".to_string()),
            previous: Some("timestamp".to_string()),
            action: "replaced".to_string(),
            status: "confirmed".to_string(),
        };
        let text_rendered_col = render_event(&event_col, RenderFormat::Text);
        assert_eq!(
            text_rendered_col.stdout,
            "replaced column-role for pagila.public.rental (col: rental_date): \"timestamp\" -> \"event_time\"\n"
        );
    }
}