a3s 0.10.5

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
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
//! Stable, source-free summaries for sandboxed `program` calls.
//!
//! Large PTC sources are implementation details, not model reasoning. This
//! module derives a bounded user-facing intent from structured invocation
//! inputs and actual completed call metadata without evaluating JavaScript.

use a3s_tui::style::strip_ansi;
use serde_json::Value;

const MAX_INLINE_CHARS: usize = 180;
const MAX_QUERY_CHARS: usize = 96;
const MAX_TOOL_GROUPS: usize = 4;
const MAX_CALL_RECORDS_TO_SCAN: usize = 256;

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ProgramPreview {
    pub(super) intent: String,
    pub(super) details: Vec<ProgramPreviewDetail>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ProgramPreviewDetail {
    pub(super) label: &'static str,
    pub(super) value: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ProgramCallDigest {
    pub(super) text: String,
    pub(super) has_failure: bool,
}

pub(super) fn summarize_program_args(args: Option<&Value>) -> Option<ProgramPreview> {
    let args = args?;
    let payload = args.get("inputs").or_else(|| args.get("input"));
    let execution_input = payload.and_then(|value| value.get("input")).or(payload);

    let explicit_intent = first_inline_text(
        args,
        &["/intent", "/inputs/intent", "/inputs/input/intent"],
        MAX_INLINE_CHARS,
    )
    .or_else(|| {
        payload
            .and_then(|value| first_object_text(value, &["description", "title"], MAX_INLINE_CHARS))
    })
    .or_else(|| {
        execution_input
            .and_then(|value| first_object_text(value, &["description", "title"], MAX_INLINE_CHARS))
    });
    let query = execution_input
        .and_then(|value| first_object_text(value, &["query", "q"], MAX_QUERY_CHARS))
        .or_else(|| {
            payload.and_then(|value| first_object_text(value, &["query", "q"], MAX_QUERY_CHARS))
        });
    let deep_research = execution_input.is_some_and(is_deep_research_input);

    let intent = explicit_intent.unwrap_or_else(|| {
        if deep_research {
            query
                .as_deref()
                .map(|query| {
                    format!("DeepResearch “{query}”: execute the coverage-driven evidence pipeline")
                })
                .unwrap_or_else(|| {
                    "Execute the coverage-driven DeepResearch evidence pipeline".to_string()
                })
        } else if let Some(query) = query.as_deref() {
            format!("Process “{query}” with a sandboxed script")
        } else if let Some(path) = args.get("path").and_then(Value::as_str) {
            format!(
                "Run workspace script {}",
                clean_inline(path, MAX_INLINE_CHARS)
            )
        } else {
            "Execute sandboxed JavaScript orchestration".to_string()
        }
    });

    let mut details = Vec::with_capacity(2);
    if deep_research {
        if let Some(plan) = execution_input.and_then(deep_research_plan) {
            details.push(ProgramPreviewDetail {
                label: "plan",
                value: plan,
            });
        }
    }
    let phase = payload.and_then(|payload| {
        if deep_research {
            deep_research_program_phase(payload)
        } else {
            program_phase(payload)
        }
    });
    if let Some(phase) = phase {
        details.push(ProgramPreviewDetail {
            label: "phase",
            value: phase,
        });
    } else if deep_research {
        let local_only = execution_input
            .and_then(|value| value.get("evidence_scope"))
            .and_then(Value::as_str)
            == Some("local_only");
        details.push(ProgramPreviewDetail {
            label: "phase",
            value: if local_only {
                "workspace retrieval → typed semantic coverage → closed review".to_string()
            } else {
                "initial retrieval → typed-gap supplement if needed → closed review".to_string()
            },
        });
    } else if let Some(scope) = allowed_tool_scope(args) {
        details.push(ProgramPreviewDetail {
            label: "scope",
            value: scope,
        });
    }
    details.truncate(2);

    Some(ProgramPreview { intent, details })
}

pub(super) fn summarize_program_calls(calls: &[Value]) -> Option<ProgramCallDigest> {
    if calls.is_empty() {
        return None;
    }

    let scanned = calls.len().min(MAX_CALL_RECORDS_TO_SCAN);
    let omitted_records = calls.len().saturating_sub(scanned);
    let mut groups: Vec<(String, usize)> = Vec::with_capacity(MAX_TOOL_GROUPS);
    let mut ungrouped_calls = 0usize;
    let mut succeeded = 0usize;
    for call in calls.iter().take(MAX_CALL_RECORDS_TO_SCAN) {
        let name = call
            .get("tool_name")
            .and_then(Value::as_str)
            .map(|value| clean_inline(value, 40))
            .filter(|value| !value.is_empty())
            .unwrap_or_else(|| "tool".to_string());
        if call.get("success").and_then(Value::as_bool) == Some(true) {
            succeeded += 1;
        }
        if let Some((_, count)) = groups.iter_mut().find(|(stored, _)| stored == &name) {
            *count += 1;
        } else if groups.len() < MAX_TOOL_GROUPS {
            groups.push((name, 1));
        } else {
            ungrouped_calls += 1;
        }
    }

    let mut route = groups
        .iter()
        .map(|(name, count)| {
            if *count > 1 {
                format!("{name} ×{count}")
            } else {
                name.clone()
            }
        })
        .collect::<Vec<_>>()
        .join("");
    if ungrouped_calls > 0 {
        route.push_str(&format!(" → +{ungrouped_calls} calls"));
    }
    let bounded_result = format!("{succeeded}/{scanned} ok");
    let result = if omitted_records > 0 {
        format!("{bounded_result} · +{omitted_records} records")
    } else {
        bounded_result
    };
    Some(ProgramCallDigest {
        text: format!("called {route} · {result}"),
        has_failure: succeeded < scanned,
    })
}

fn is_deep_research_input(value: &Value) -> bool {
    let Some(object) = value.as_object() else {
        return false;
    };
    object.contains_key("evidence_scope")
        && (object.get("inquiry_host_managed").and_then(Value::as_bool) == Some(true)
            || value
                .pointer("/loop_contract/pattern")
                .and_then(Value::as_str)
                == Some("minimal-deep-research"))
}

fn deep_research_plan(value: &Value) -> Option<String> {
    let scope = value
        .get("evidence_scope")
        .and_then(Value::as_str)
        .map(|scope| match scope {
            "web_and_workspace" => "web + workspace".to_string(),
            "local_only" => "local only".to_string(),
            other => clean_inline(other, 32),
        });
    let searches = value
        .pointer("/loop_contract/hard_caps/max_searches")
        .and_then(Value::as_u64);
    let fetches = value
        .pointer("/loop_contract/hard_caps/max_fetches")
        .and_then(Value::as_u64);

    let mut parts = Vec::new();
    if let Some(scope) = scope.filter(|scope| !scope.is_empty()) {
        parts.push(scope);
    }
    let local_only = value.get("evidence_scope").and_then(Value::as_str) == Some("local_only");
    parts.push(if local_only {
        "one workspace retrieval".to_string()
    } else {
        "≤2 typed-coverage passes".to_string()
    });
    if !local_only {
        if let Some(searches) = searches {
            parts.push(format!("{searches} searches"));
        }
        if let Some(fetches) = fetches {
            parts.push(format!("{fetches} fetches"));
        }
    }
    Some(parts.join(" · "))
}

fn program_phase(payload: &Value) -> Option<String> {
    match payload.get("kind").and_then(Value::as_str) {
        Some("workflow") => {
            let completed = payload
                .get("step_outputs")
                .and_then(Value::as_object)
                .map_or(0, serde_json::Map::len);
            let failed = payload
                .get("step_failures")
                .and_then(Value::as_object)
                .map_or(0, serde_json::Map::len);
            Some(if completed == 0 && failed == 0 {
                "plan the initial evidence routes".to_string()
            } else if failed > 0 {
                format!("review {completed} completed / {failed} failed steps and choose recovery")
            } else {
                format!("review {completed} completed steps and choose the next route")
            })
        }
        Some("step") => {
            let step = payload
                .get("step_name")
                .and_then(Value::as_str)
                .map(|value| clean_inline(value, 64));
            Some(match step.as_deref() {
                Some("direct_web_research") => {
                    "collect and validate direct web evidence".to_string()
                }
                Some("runtime_preflight") => "verify remote research capability".to_string(),
                Some("runtime_research") => "run remote evidence collection".to_string(),
                Some(step) if step.starts_with("local_research") => {
                    "run a focused local research round".to_string()
                }
                Some(step) if step.starts_with("local_fallback") => {
                    "run the local evidence fallback".to_string()
                }
                Some(step) if !step.is_empty() => format!("execute workflow step {step}"),
                _ => "execute one workflow step".to_string(),
            })
        }
        _ => None,
    }
}

fn deep_research_program_phase(payload: &Value) -> Option<String> {
    match payload.get("kind").and_then(Value::as_str) {
        Some("workflow") => {
            let completed = payload
                .get("step_outputs")
                .and_then(Value::as_object)
                .map_or(0, serde_json::Map::len);
            let failed = payload
                .get("step_failures")
                .and_then(Value::as_object)
                .map_or(0, serde_json::Map::len);
            Some(if completed == 0 && failed == 0 {
                "run initial retrieval and typed semantic coverage".to_string()
            } else if failed > 0 {
                "settle failures without opening an untyped retrieval route".to_string()
            } else {
                "close typed gaps from the existing catalog, then seal evidence".to_string()
            })
        }
        Some("step") => Some(
            match payload.get("step_name").and_then(Value::as_str) {
                Some("retrieve_web") => "run the initial web retrieval pass",
                Some("retrieve_supplemental_web") => {
                    "fetch typed-gap candidates from the existing catalog"
                }
                Some("retrieve_local") => "collect bounded workspace evidence once",
                Some("generate_object") => "select IDs from the closed chunk catalog",
                _ => "execute one bounded stage of the fixed pipeline",
            }
            .to_string(),
        ),
        _ => None,
    }
}

fn allowed_tool_scope(args: &Value) -> Option<String> {
    let tools = args.get("allowed_tools")?.as_array()?;
    let mut names = tools
        .iter()
        .filter_map(Value::as_str)
        .map(|value| clean_inline(value, 40))
        .filter(|value| !value.is_empty())
        .take(MAX_TOOL_GROUPS + 1)
        .collect::<Vec<_>>();
    if names.is_empty() {
        return None;
    }
    let omitted = names.len().saturating_sub(MAX_TOOL_GROUPS);
    names.truncate(MAX_TOOL_GROUPS);
    let mut summary = names.join(" · ");
    if omitted > 0 || tools.len() > MAX_TOOL_GROUPS {
        summary.push_str(&format!(
            " · +{}",
            tools.len().saturating_sub(MAX_TOOL_GROUPS)
        ));
    }
    Some(summary)
}

fn first_inline_text(root: &Value, pointers: &[&str], max_chars: usize) -> Option<String> {
    pointers.iter().find_map(|pointer| {
        root.pointer(pointer)
            .and_then(Value::as_str)
            .map(|value| clean_inline(value, max_chars))
            .filter(|value| !value.is_empty())
    })
}

fn first_object_text(value: &Value, keys: &[&str], max_chars: usize) -> Option<String> {
    keys.iter().find_map(|key| {
        value
            .get(*key)
            .and_then(Value::as_str)
            .map(|value| clean_inline(value, max_chars))
            .filter(|value| !value.is_empty())
    })
}

fn clean_inline(value: &str, max_chars: usize) -> String {
    let without_ansi = strip_ansi(value);
    let collapsed = without_ansi
        .chars()
        .map(|ch| if ch.is_control() { ' ' } else { ch })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let mut chars = collapsed.chars();
    let mut bounded = chars.by_ref().take(max_chars).collect::<String>();
    if chars.next().is_some() {
        bounded.push('');
    }
    bounded
}

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

    #[test]
    fn deep_research_preview_uses_structured_intent_instead_of_source_wrapper() {
        let preview = summarize_program_args(Some(&json!({
            "type": "script",
            "source": "async function run(ctx, inputs) { return {}; }",
            "inputs": {
                "kind": "workflow",
                "step_outputs": {},
                "step_failures": {},
                "input": {
                    "query": "Nimbus\u{1b}[31m 支持状态",
                    "evidence_scope": "web_and_workspace",
                    "inquiry_host_managed": true,
                    "loop_contract": {
                        "pattern": "minimal-deep-research",
                        "hard_caps": {
                            "max_searches": 4,
                            "max_fetches": 8
                        }
                    }
                }
            }
        })))
        .unwrap();

        assert!(preview.intent.contains("DeepResearch “Nimbus 支持状态”"));
        assert!(!preview.intent.contains("async function run"));
        assert_eq!(preview.details[0].label, "plan");
        assert_eq!(
            preview.details[0].value,
            "web + workspace · ≤2 typed-coverage passes · ≤4 searches · ≤8 fetches"
        );
        assert_eq!(
            preview.details[1].value,
            "run initial retrieval and typed semantic coverage"
        );
    }

    #[test]
    fn workflow_phase_changes_after_steps_complete() {
        let preview = summarize_program_args(Some(&json!({
            "type": "script",
            "inputs": {
                "kind": "workflow",
                "step_outputs": {"seed": {}, "verify": {}},
                "step_failures": {},
                "input": {"query": "status"}
            }
        })))
        .unwrap();

        assert_eq!(preview.details[0].label, "phase");
        assert_eq!(
            preview.details[0].value,
            "review 2 completed steps and choose the next route"
        );
    }

    #[test]
    fn workflow_step_preview_names_the_current_operation() {
        let preview = summarize_program_args(Some(&json!({
            "type": "script",
            "inputs": {
                "kind": "step",
                "step_name": "direct_web_research",
                "input": {"query": "status"}
            }
        })))
        .unwrap();

        assert_eq!(
            preview.details[0].value,
            "collect and validate direct web evidence"
        );
    }

    #[test]
    fn completed_calls_are_aggregated_into_one_bounded_digest() {
        let calls = json!([
            {"tool_name": "web_search", "success": true},
            {"tool_name": "web_fetch", "success": true},
            {"tool_name": "web_search", "success": false}
        ]);
        let digest = summarize_program_calls(calls.as_array().unwrap()).unwrap();

        assert_eq!(digest.text, "called web_search ×2 → web_fetch · 2/3 ok");
        assert!(digest.has_failure);
    }

    #[test]
    fn completed_call_digest_has_a_hard_scan_limit() {
        let calls = (0..300)
            .map(|index| {
                json!({
                    "tool_name": format!("tool-{index}"),
                    "success": true
                })
            })
            .collect::<Vec<_>>();
        let digest = summarize_program_calls(&calls).unwrap();

        assert!(digest.text.contains("+252 calls"), "{}", digest.text);
        assert!(
            digest.text.contains("256/256 ok · +44 records"),
            "{}",
            digest.text
        );
        assert!(!digest.has_failure);
    }

    #[test]
    fn path_script_fallback_never_reads_or_echoes_source() {
        let preview = summarize_program_args(Some(&json!({
            "type": "script",
            "path": "scripts/report.mjs",
            "source": "secret implementation"
        })))
        .unwrap();

        assert_eq!(preview.intent, "Run workspace script scripts/report.mjs");
        assert!(!preview.intent.contains("secret"));
    }
}