basis-acp 0.2.0

The Agent Client Protocol adapter over basis: the same event stream and the same seams, served to editors and web UIs.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! basis's [`Event`] stream, as ACP `session/update` notifications.
//!
//! This is the reason [`Event`] exists. mentra's `SessionEvent` is normalized
//! once, in `event/mapping.rs`, and every surface downstream — JSONL, ACP,
//! whatever comes next — maps from basis's own shape. Nothing here touches
//! mentra.
//!
//! The match is exhaustive with no wildcard, for the same reason the mentra
//! mapping is: a new [`Event`] variant should break this build rather than
//! quietly stop reaching ACP clients.

use agent_client_protocol::schema::v1::{
    ContentBlock, ContentChunk, SessionUpdate, TextContent, ToolCall, ToolCallStatus,
    ToolCallUpdate, ToolCallUpdateFields, ToolKind,
};
use serde_json::Value;

use basis::{
    event::{Event, Mutability},
    tools::SPAWN,
};

/// Maps one basis event to an ACP session update.
///
/// `None` where ACP has no place for it — basis's own bookends, and the
/// housekeeping events (usage, compaction, retries) that ACP models
/// differently or not at all. Those still reach a JSONL consumer; they are
/// simply not part of this protocol's vocabulary.
pub fn session_update(event: &Event) -> Option<SessionUpdate> {
    let update = match event {
        // basis's bookends. `session/prompt` returning is what tells an ACP
        // client the turn is over, so repeating it as an update would be
        // noise.
        Event::RunStarted { .. } | Event::RunFinished { .. } => return None,

        // The client sent this; echoing it back would double it in the UI.
        Event::UserMessage { .. } => return None,

        Event::AssistantDelta { text } => SessionUpdate::AgentMessageChunk(chunk(text)),
        Event::AssistantReasoningDelta { text } => SessionUpdate::AgentThoughtChunk(chunk(text)),

        // The deltas already streamed this text. Sending the assembled message
        // too would render it twice.
        Event::AssistantMessage { .. } => return None,

        Event::ToolQueued {
            tool_call_id,
            tool_name,
            summary,
            mutability,
            input,
        } => SessionUpdate::ToolCall(
            ToolCall::new(tool_call_id.clone(), title(summary, tool_name))
                .kind(tool_kind(tool_name, *mutability, input))
                .status(ToolCallStatus::Pending)
                .raw_input(input.clone()),
        ),

        Event::ToolStarted { tool_call_id, .. } => {
            SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
                tool_call_id.clone(),
                ToolCallUpdateFields::new().status(ToolCallStatus::InProgress),
            ))
        }

        // ACP has no progress field, so progress becomes the title: a client
        // showing the call sees it change as the work proceeds.
        Event::ToolProgress {
            tool_call_id,
            progress,
            ..
        } => SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
            tool_call_id.clone(),
            ToolCallUpdateFields::new().title(progress.clone()),
        )),

        Event::ToolCompleted {
            tool_call_id,
            summary,
            is_error,
            ..
        } => SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
            tool_call_id.clone(),
            ToolCallUpdateFields::new()
                .status(if *is_error {
                    ToolCallStatus::Failed
                } else {
                    ToolCallStatus::Completed
                })
                .content(vec![text_block(summary).into()]),
        )),

        // The request itself is a `session/request_permission` round trip, not
        // an update — see `acp/approver.rs`. The resolution is reflected by
        // the tool call's own status.
        Event::PermissionRequested { .. } | Event::PermissionResolved { .. } => return None,

        // Concurrent work has no ACP vocabulary yet. Surfacing it as a thought
        // keeps the client informed instead of dropping it silently.
        Event::TaskUpdated {
            title: task_title,
            status,
            ..
        } => SessionUpdate::AgentThoughtChunk(chunk(&format!("[{status:?}] {task_title}"))),

        // Housekeeping: real, and worth having on the JSONL stream, but not
        // something an ACP client renders. `UsageUpdate` is about the context
        // window rather than per-turn token counts, so basis does not pretend
        // these are the same thing.
        Event::CompactionStarted { .. }
        | Event::CompactionCompleted { .. }
        | Event::MemoryUpdated { .. }
        | Event::Usage { .. }
        | Event::Branched { .. } => return None,

        // Anything the operator should see becomes a thought chunk: a retry or
        // a recoverable error explains a pause the user is already watching.
        Event::Notice { message, .. } => SessionUpdate::AgentThoughtChunk(chunk(message)),
        Event::Retry {
            error,
            attempt,
            max_attempts,
            ..
        } => SessionUpdate::AgentThoughtChunk(chunk(&format!(
            "retrying after {error} (attempt {attempt}/{max_attempts})"
        ))),
        Event::Error { message, .. } => {
            SessionUpdate::AgentThoughtChunk(chunk(&format!("error: {message}")))
        }
    };

    Some(update)
}

fn chunk(text: &str) -> ContentChunk {
    ContentChunk::new(text_block(text))
}

fn text_block(text: &str) -> ContentBlock {
    ContentBlock::Text(TextContent::new(text.to_string()))
}

/// What to call the tool call in a client's UI.
///
/// mentra's summary is written for a person ("Run 'cargo test'"), so it is the
/// better title when there is one; the tool's name is the fallback.
fn title(summary: &str, tool_name: &str) -> String {
    if summary.trim().is_empty() {
        tool_name.to_string()
    } else {
        summary.to_string()
    }
}

/// Classifies a mentra tool for ACP's icon vocabulary.
///
/// Name-based, because for every tool but one that is all the information
/// there is — mentra reports a name and a mutability, not a category. Unknown
/// names fall back to mutability, and then to `Other`: a wrong icon is worse
/// than no icon, and a tool basis has never heard of is exactly the case where
/// guessing is unwise.
///
/// [`SPAWN`] is the exception, and the reason this takes the call's input at
/// all. Since ADR-0016 one name carries two acts — a command and a delegation —
/// so a name-keyed answer is necessarily wrong for one of them.
fn tool_kind(tool_name: &str, mutability: Mutability, input: &Value) -> ToolKind {
    if tool_name == SPAWN {
        return spawn_kind(input);
    }

    match tool_name {
        "shell" | "bash" | "command" | "background_command" => ToolKind::Execute,
        "files" | "read" | "read_file" => match mutability {
            Mutability::ReadOnly => ToolKind::Read,
            _ => ToolKind::Edit,
        },
        "write" | "write_file" | "edit" | "edit_file" | "apply_patch" => ToolKind::Edit,
        "delete" | "remove" => ToolKind::Delete,
        "move" | "rename" => ToolKind::Move,
        "search" | "grep" | "glob" | "find" => ToolKind::Search,
        "fetch" | "web_fetch" | "http" => ToolKind::Fetch,
        "think" | "load_skill" => ToolKind::Think,
        _ => match mutability {
            Mutability::ReadOnly => ToolKind::Read,
            Mutability::Mutating => ToolKind::Edit,
            Mutability::Unknown => ToolKind::Other,
        },
    }
}

/// The field `spawn` takes its one string in.
///
/// A literal because `basis` keeps the name private; see [`spawn_kind`] for
/// what that costs and what it does not.
const SPAWN_INPUT: &str = "input";

/// What ACP calls handing work to a subagent, which is nothing.
///
/// `ToolKind` in schema v1 offers `Read`, `Edit`, `Delete`, `Move`, `Search`,
/// `Execute`, `Think`, `Fetch`, `SwitchMode` and `Other`, and none of them
/// means delegation. `Think` is the nearest name and the wrong one: it promises
/// internal reasoning with nothing outside the process changed, while a
/// delegation is consequential enough that basis puts it to the approver, and the
/// subagent on the other side of it holds `spawn` in its own turn. Rendering
/// that as a thought would contradict the permission prompt the client has just
/// been asked to answer.
///
/// So `Other` — the schema's own default, and an honest "no category" — until
/// something can say `delegate`. ACP v2's `ToolKind::Unknown(String)` reserves
/// leading-underscore values for exactly this kind of extension; v1, which this
/// crate speaks, has no such escape.
const DELEGATION: ToolKind = ToolKind::Other;

/// `spawn`'s kind, which its *mode* decides rather than its name (ADR-0016).
///
/// The mode is re-derived from the raw string here, and that is a knowing
/// second reading of the convention `basis::tools::spawn` parses exactly
/// once. It is not free: if the two ever disagree — a new escape, a different
/// trim — a client renders the wrong icon and nothing says so. What keeps it
/// tolerable is that this path decides nothing. The typed `{mode, body, cwd}`
/// is what reaches the approver, the rule store, the hooks and the audit trail;
/// what reaches ACP is a `ToolQueued` event carrying the string the model
/// wrote, and basis exports no reader for it. The fix is that reader,
/// exported from the crate that owns the convention — not a second copy that
/// grows.
fn spawn_kind(input: &Value) -> ToolKind {
    let Some(body) = input.get(SPAWN_INPUT).and_then(Value::as_str) else {
        // Nothing to read, and spawn's own preview will refuse this call before
        // it runs. Reported as the stronger of the two modes for the reason
        // spawn's static descriptor is `Process`: a tool that can run commands
        // should not describe itself as something milder when there is nothing
        // per-call to go on.
        return ToolKind::Execute;
    };

    match body.trim().strip_prefix('!') {
        // `!!` is the escape a task whose own text starts with `!` is written
        // with, so it is a delegation and not a command.
        Some(rest) if rest.starts_with('!') => DELEGATION,
        Some(_) => ToolKind::Execute,
        None => DELEGATION,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use basis::event::{NoticeSeverity, RunOutcome};
    use serde_json::json;

    fn text_of(chunk: &ContentChunk) -> String {
        match &chunk.content {
            ContentBlock::Text(text) => text.text.clone(),
            other => panic!("expected text content, got {other:?}"),
        }
    }

    #[test]
    fn assistant_deltas_become_message_chunks() {
        let update = session_update(&Event::AssistantDelta {
            text: "hello".to_string(),
        })
        .expect("mapped");

        let SessionUpdate::AgentMessageChunk(chunk) = update else {
            panic!("expected an agent message chunk");
        };
        assert_eq!(text_of(&chunk), "hello");
    }

    #[test]
    fn reasoning_is_a_thought_not_a_message() {
        // Rendering private reasoning as the answer would be a real leak of
        // one into the other.
        let update = session_update(&Event::AssistantReasoningDelta {
            text: "considering".to_string(),
        })
        .expect("mapped");

        assert!(matches!(update, SessionUpdate::AgentThoughtChunk(_)));
    }

    #[test]
    fn the_assembled_message_is_not_sent_after_its_own_deltas() {
        assert_eq!(
            session_update(&Event::AssistantMessage {
                text: "hello".to_string()
            }),
            None,
            "the deltas already carried this text; sending it again renders it twice"
        );
    }

    #[test]
    fn lan_bookends_are_not_acp_updates() {
        assert_eq!(
            session_update(&Event::RunFinished {
                outcome: RunOutcome::Ok,
                stopped_by: None
            }),
            None
        );
        assert_eq!(
            session_update(&Event::UserMessage {
                text: "hi".to_string()
            }),
            None,
            "the client sent this; echoing it doubles it"
        );
    }

    #[test]
    fn a_queued_tool_call_carries_its_title_kind_and_input() {
        let update = session_update(&Event::ToolQueued {
            tool_call_id: "c1".to_string(),
            tool_name: "shell".to_string(),
            summary: "Run 'cargo test'".to_string(),
            mutability: Mutability::Mutating,
            input: json!({"command": "cargo test"}),
        })
        .expect("mapped");

        let SessionUpdate::ToolCall(call) = update else {
            panic!("expected a tool call");
        };
        assert_eq!(&*call.tool_call_id.0, "c1");
        assert_eq!(call.title, "Run 'cargo test'");
        assert_eq!(call.kind, ToolKind::Execute);
        assert_eq!(call.status, ToolCallStatus::Pending);
        assert_eq!(
            call.raw_input,
            Some(json!({"command": "cargo test"})),
            "a client showing what a call would do needs its real input"
        );
    }

    #[test]
    fn a_call_with_no_summary_falls_back_to_its_name() {
        let update = session_update(&Event::ToolQueued {
            tool_call_id: "c1".to_string(),
            tool_name: "files".to_string(),
            summary: "   ".to_string(),
            mutability: Mutability::ReadOnly,
            input: json!({}),
        })
        .expect("mapped");

        let SessionUpdate::ToolCall(call) = update else {
            panic!("expected a tool call");
        };
        assert_eq!(call.title, "files", "a blank title tells a client nothing");
    }

    #[test]
    fn a_completed_call_reports_success_or_failure() {
        for (is_error, expected) in [
            (false, ToolCallStatus::Completed),
            (true, ToolCallStatus::Failed),
        ] {
            let update = session_update(&Event::ToolCompleted {
                tool_call_id: "c1".to_string(),
                tool_name: "shell".to_string(),
                summary: "output".to_string(),
                is_error,
            })
            .expect("mapped");

            let SessionUpdate::ToolCallUpdate(call) = update else {
                panic!("expected a tool call update");
            };
            assert_eq!(call.fields.status, Some(expected));
        }
    }

    #[test]
    fn a_started_call_goes_in_progress() {
        let update = session_update(&Event::ToolStarted {
            tool_call_id: "c1".to_string(),
            tool_name: "shell".to_string(),
        })
        .expect("mapped");

        let SessionUpdate::ToolCallUpdate(call) = update else {
            panic!("expected a tool call update");
        };
        assert_eq!(call.fields.status, Some(ToolCallStatus::InProgress));
    }

    #[test]
    fn permission_events_are_a_round_trip_not_an_update() {
        assert_eq!(
            session_update(&Event::PermissionRequested {
                request_id: "r1".to_string(),
                tool_call_id: "c1".to_string(),
                tool_name: "shell".to_string(),
                description: "wants to run".to_string(),
                preview: json!({}),
            }),
            None,
            "a permission request is session/request_permission, not session/update"
        );
    }

    #[test]
    fn an_operator_facing_notice_reaches_the_client() {
        let update = session_update(&Event::Notice {
            severity: NoticeSeverity::Warning,
            message: "context is nearly full".to_string(),
        })
        .expect("mapped");

        let SessionUpdate::AgentThoughtChunk(chunk) = update else {
            panic!("expected a thought chunk");
        };
        assert!(text_of(&chunk).contains("context is nearly full"));
    }

    #[test]
    fn tool_kinds_follow_the_name_then_the_mutability() {
        let no_input = json!({});

        assert_eq!(
            tool_kind("shell", Mutability::Mutating, &no_input),
            ToolKind::Execute
        );
        assert_eq!(
            tool_kind("files", Mutability::ReadOnly, &no_input),
            ToolKind::Read
        );
        assert_eq!(
            tool_kind("files", Mutability::Mutating, &no_input),
            ToolKind::Edit
        );
        assert_eq!(
            tool_kind("grep", Mutability::ReadOnly, &no_input),
            ToolKind::Search
        );

        // An unknown tool falls back to what mentra says it does, and admits
        // ignorance when mentra does not know either.
        assert_eq!(
            tool_kind("something_new", Mutability::ReadOnly, &no_input),
            ToolKind::Read
        );
        assert_eq!(
            tool_kind("something_new", Mutability::Unknown, &no_input),
            ToolKind::Other
        );
    }

    #[test]
    fn spawn_is_classified_by_its_mode_rather_than_by_its_name() {
        // The one tool whose name cannot answer for it. mentra reports
        // `Unknown` mutability on every queued call, so before ADR-0016's map
        // both of these rendered as `Other`.
        assert_eq!(
            tool_kind(
                SPAWN,
                Mutability::Unknown,
                &json!({"input": "!cargo test -q"})
            ),
            ToolKind::Execute,
            "a command is what `shell` always was"
        );
        assert_eq!(
            tool_kind(
                SPAWN,
                Mutability::Unknown,
                &json!({"input": "find every TODO under src/"})
            ),
            ToolKind::Other,
            "ACP v1 has no kind meaning delegation, and `Think` would understate it"
        );
        assert_eq!(
            tool_kind(
                SPAWN,
                Mutability::Unknown,
                &json!({"input": "  !!urgent: rewrite the README"})
            ),
            ToolKind::Other,
            "`!!` escapes a task whose own text starts with `!`; it is not a command"
        );
    }

    #[test]
    fn an_unreadable_spawn_call_reports_the_stronger_mode() {
        // Nothing per-call to go on, so this answers as spawn's static
        // descriptor does: `Process`, never the milder of the two.
        for input in [json!({}), json!({"input": 7}), json!("!cargo test")] {
            assert_eq!(
                tool_kind(SPAWN, Mutability::Unknown, &input),
                ToolKind::Execute,
                "{input}"
            );
        }
    }

    #[test]
    fn a_queued_spawn_command_reaches_the_client_as_an_execution() {
        // The mode lives in the input, so this pins the wiring as well as the
        // classifier: a call site that forgot to pass the input would still
        // satisfy the tests above.
        let update = session_update(&Event::ToolQueued {
            tool_call_id: "c1".to_string(),
            tool_name: SPAWN.to_string(),
            summary: "Run 'cargo test'".to_string(),
            mutability: Mutability::Unknown,
            input: json!({"input": "!cargo test"}),
        })
        .expect("mapped");

        let SessionUpdate::ToolCall(call) = update else {
            panic!("expected a tool call");
        };
        assert_eq!(call.kind, ToolKind::Execute);
    }
}