basemind 0.10.1

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 10+ coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! Request / response shapes for the agent-comms MCP tools.
//!
//! Parameter structs derive `Deserialize + Serialize + JsonSchema` and use the validated
//! [`RoomId`](crate::comms::ids::RoomId) / [`AgentId`](crate::comms::ids::AgentId) newtypes for
//! identifier fields so a malformed id is rejected at the serde boundary rather than reaching
//! the broker. Response structs serialize the broker's [`MessageMeta`] front-matter directly —
//! history and inbox tools return front-matter ONLY; bodies come from `message_get`.

#![cfg(all(feature = "comms", any(unix, windows)))]

use serde::{Deserialize, Serialize};

use crate::comms::cursor::Cursor;
use crate::comms::ids::RoomId;
use crate::comms::model::{Room, RoomScope};
use crate::comms::protocol::SeqMeta;

// ─── agent_register ───────────────────────────────────────────────────────────────────────

/// Params for `agent_register`: announce or update this agent's A2A card.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct AgentRegisterParams {
    /// Human-readable agent name.
    #[serde(default)]
    pub name: String,
    /// One-line description of the agent's purpose.
    #[serde(default)]
    pub description: String,
    /// Agent version string (e.g. "1.0.0").
    #[serde(default)]
    pub version: String,
    /// Optional skill labels advertised to peers.
    #[serde(default)]
    pub skills: Vec<String>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `agent_register`.
#[derive(Debug, Serialize)]
pub(super) struct AgentRegisterResponse {
    /// The agent id the card was registered under.
    pub agent_id: String,
    /// Always true on success.
    pub registered: bool,
}

// ─── agent_list ───────────────────────────────────────────────────────────────────────────

/// Params for `agent_list`: enumerate known agents, optionally restricted to one room.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct AgentListParams {
    /// Restrict to subscribers of this room when set.
    #[serde(default)]
    pub room: Option<RoomId>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// One agent row in an `agent_list` response (front-matter view of an `AgentRecord`).
#[derive(Debug, Serialize)]
pub(super) struct AgentSummary {
    /// Stable agent identity.
    pub agent_id: String,
    /// Self-described name.
    pub name: String,
    /// Self-described description.
    pub description: String,
    /// Self-described version.
    pub version: String,
    /// Advertised skill labels.
    pub skills: Vec<String>,
    /// First-seen time, microseconds since the unix epoch.
    pub first_seen: i64,
    /// Last-seen time, microseconds since the unix epoch.
    pub last_seen: i64,
}

/// Response for `agent_list`.
#[derive(Debug, Serialize)]
pub(super) struct AgentListResponse {
    /// Number of agents returned.
    pub total: usize,
    /// The agent rows.
    pub agents: Vec<AgentSummary>,
}

// ─── room scope (shared input shape) ────────────────────────────────────────────────────────

/// Room-scope selector for `room_create`. Mirrors [`RoomScope`] but is a flat, agent-friendly
/// MCP input: pick exactly one of `remote` / `path_prefix` / `global`.
#[derive(Debug, Clone, Default, Deserialize, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ScopeInput {
    /// Scope to a normalised git remote (every clone of it auto-joins).
    Remote(String),
    /// Scope to a filesystem path prefix (an agent at/below it auto-joins).
    PathPrefix(std::path::PathBuf),
    /// Scope to a terminal session id (a parent + child sharing the session auto-join).
    Session(String),
    /// Scope to every agent on the machine. Reserve `global` for MACHINE-WIDE ops coordination
    /// (resource / CPU contention, shared-host scheduling), NOT general per-repo chat — use a repo
    /// room (`remote` / `path_prefix`, via `get_or_create_chat_room_for_path`) for work in a repo.
    #[default]
    Global,
}

impl From<ScopeInput> for RoomScope {
    fn from(value: ScopeInput) -> Self {
        match value {
            ScopeInput::Remote(r) => RoomScope::Remote(r),
            ScopeInput::PathPrefix(p) => RoomScope::PathPrefix(p),
            ScopeInput::Session(s) => RoomScope::Session(s),
            ScopeInput::Global => RoomScope::Global,
        }
    }
}

// ─── room_create ────────────────────────────────────────────────────────────────────────────

/// Params for `room_create`.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomCreateParams {
    /// Id of the room to create.
    pub room: RoomId,
    /// Scope governing which agents auto-join. Defaults to `global`.
    #[serde(default)]
    pub scope: ScopeInput,
    /// Optional human-readable title.
    #[serde(default)]
    pub title: Option<String>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// A room front-matter view shared by `room_create` and `room_list`.
#[derive(Debug, Serialize)]
pub(super) struct RoomSummary {
    /// Stable room id.
    pub room_id: String,
    /// Human-readable title.
    pub title: String,
    /// Creation time, microseconds since the unix epoch.
    pub created_at: i64,
    /// Last post time, microseconds since the unix epoch. `0` when the room has never had a post.
    pub last_activity_micros: i64,
    /// True when the room is STALE: either it has never had a post (`last_activity == 0`) or its
    /// last post is older than the staleness window. A stale room's chatter is unlikely to be
    /// relevant to current work — surface but de-prioritise it.
    pub stale: bool,
}

/// The staleness window for a room, in hours. A room whose last post is older than this — or which
/// has never had a post — is flagged `stale` in a [`RoomSummary`]. 168h = 7 days.
pub(super) const STALE_AFTER_HOURS: i64 = 168;

impl RoomSummary {
    /// Build a room summary, computing `stale` against `now_micros` (microseconds since the unix
    /// epoch). A room with no activity (`last_activity == 0`) is treated as stale: there is no
    /// recent chatter to anchor it to current work.
    pub(super) fn from_room(room: &Room, now_micros: i64) -> Self {
        let last = room.last_activity;
        let window_micros = STALE_AFTER_HOURS * 3_600_000_000;
        let stale = last == 0 || (now_micros - last) > window_micros;
        Self {
            room_id: room.room_id.as_str().to_string(),
            title: room.title.clone(),
            created_at: room.created_at,
            last_activity_micros: last,
            stale,
        }
    }
}

/// Response for `room_create`.
#[derive(Debug, Serialize)]
pub(super) struct RoomCreateResponse {
    /// The created (or re-confirmed) room.
    pub room: RoomSummary,
}

// ─── room_list ──────────────────────────────────────────────────────────────────────────────

/// Params for `room_list`: list rooms whose scope matches the calling agent's chain. No fields
/// — scope context (remote + cwd) is injected by the server from its root.
#[derive(Debug, Clone, Default, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomListParams {}

/// Response for `room_list`.
#[derive(Debug, Serialize)]
pub(super) struct RoomListResponse {
    /// Number of rooms returned.
    pub total: usize,
    /// The room rows.
    pub rooms: Vec<RoomSummary>,
}

// ─── room_join / room_leave ──────────────────────────────────────────────────────────────────

/// Params for `room_join`.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomJoinParams {
    /// The room to join (subscribe to).
    pub room: RoomId,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Params for `room_leave`.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomLeaveParams {
    /// The room to leave (unsubscribe from).
    pub room: RoomId,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `room_join` / `room_leave`.
#[derive(Debug, Serialize)]
pub(super) struct RoomMembershipResponse {
    /// The room acted on.
    pub room: String,
    /// True after a successful join.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub joined: bool,
    /// True after a successful leave.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub left: bool,
}

// ─── room_post ───────────────────────────────────────────────────────────────────────────────

/// Params for `room_post`.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomPostParams {
    /// Target room.
    pub room: RoomId,
    /// Short human subject line.
    pub subject: String,
    /// Message body (markdown). Empty when omitted.
    #[serde(default)]
    pub body: Option<String>,
    /// Free-form tags for filtering.
    #[serde(default)]
    pub tags: Option<Vec<String>>,
    /// Id of the message this one replies to, for threading.
    #[serde(default)]
    pub reply_to: Option<String>,
    /// Glob / path patterns (or repo / workspace tags) describing WHERE this message applies, so
    /// peers can filter relevance from front-matter without fetching the body. Empty when omitted.
    #[serde(default)]
    pub scope: Option<Vec<String>>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `room_post`.
#[derive(Debug, Serialize)]
pub(super) struct RoomPostResponse {
    /// The id of the message just stored.
    pub message_id: String,
}

// ─── room_history ────────────────────────────────────────────────────────────────────────────

/// Params for `room_history`: read a room's front-matter, oldest-first, paginated.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct RoomHistoryParams {
    /// The room to read.
    pub room: RoomId,
    /// Resume token from a previous page's `next_cursor` (opaque string).
    #[serde(default)]
    pub cursor: Option<String>,
    /// Maximum messages to return (default 100, max 1000).
    #[serde(default)]
    pub limit: Option<u32>,
    /// Only return messages from the last N hours; defaults to 24. Pass 0 for ALL history.
    #[serde(default)]
    pub since_hours: Option<u32>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Front-matter view of a message. Surfaces [`MessageMeta`] front-matter plus its per-room `seq`
/// — NO body. Fetch the body with `message_get`. `seq` lets callers drive `inbox_ack` (the
/// `to_seq` bulk mode) without an extra round-trip.
#[derive(Debug, Serialize)]
pub(super) struct MessageFrontMatter {
    /// Globally unique message id (pass to `message_get` or `inbox_ack`).
    pub id: String,
    /// Room the message was posted to.
    pub room: String,
    /// Authoring agent.
    pub from: String,
    /// Short human subject line.
    pub subject: String,
    /// Post time, microseconds since the unix epoch.
    pub ts_micros: i64,
    /// Age of the message in whole seconds at read time (`now - ts`, floored at 0). Lets an agent
    /// gauge staleness without converting `ts_micros` against a wall clock itself.
    pub age_secs: i64,
    /// Free-form tags.
    pub tags: Vec<String>,
    /// Glob / path patterns describing where the message applies (empty when unscoped).
    pub scope: Vec<String>,
    /// Id of the message this one replies to, if any.
    pub reply_to: Option<String>,
    /// Per-room sequence number — the message's position in its room's append-only log. Pass as
    /// `inbox_ack`'s `to_seq` to bulk-ack everything up to and including this message.
    pub seq: u64,
    /// Length of the separately-stored body in bytes.
    pub body_len: u32,
    /// Hex SHA-256 of the body for integrity.
    pub body_sha: String,
}

impl MessageFrontMatter {
    /// Build a front-matter row from a [`SeqMeta`], stamping `age_secs` against `now_micros`
    /// (microseconds since the unix epoch). `now` is threaded in rather than read here so a whole
    /// page shares one clock reading and the conversion stays testable.
    pub(super) fn from_seq_meta(sm: &SeqMeta, now_micros: i64) -> Self {
        let meta = &sm.meta;
        Self {
            id: meta.id.clone(),
            room: meta.room.as_str().to_string(),
            from: meta.from.as_str().to_string(),
            subject: meta.subject.clone(),
            ts_micros: meta.ts_micros,
            age_secs: ((now_micros - meta.ts_micros) / 1_000_000).max(0),
            tags: meta.tags.clone(),
            scope: meta.scope.clone(),
            reply_to: meta.reply_to.clone(),
            seq: sm.seq,
            body_len: meta.body_len,
            body_sha: meta.body_sha.clone(),
        }
    }
}

/// Response for `room_history`.
#[derive(Debug, Serialize)]
pub(super) struct RoomHistoryResponse {
    /// Number of messages in this page.
    pub total: usize,
    /// Front-matter rows, oldest-first.
    pub messages: Vec<MessageFrontMatter>,
    /// Opaque cursor for the next page; absent means no more results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<Cursor>,
}

// ─── message_get ─────────────────────────────────────────────────────────────────────────────

/// Params for `message_get`: fetch a single message body by id.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct MessageGetParams {
    /// The message id (the `id` of a front-matter record).
    pub message_id: String,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `message_get`.
#[derive(Debug, Serialize)]
pub(super) struct MessageGetResponse {
    /// The message id queried.
    pub message_id: String,
    /// True when a body was found for the id.
    pub found: bool,
    /// The body decoded as UTF-8 (lossy — bodies are markdown). `None` when the id is unknown.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

// ─── inbox_read ──────────────────────────────────────────────────────────────────────────────

/// Params for `inbox_read`: read new front-matter across subscribed rooms.
#[derive(Debug, Clone, Default, Deserialize, Serialize, schemars::JsonSchema)]
pub struct InboxReadParams {
    /// Resume token from a previous page's `next_cursor` (opaque string).
    #[serde(default)]
    pub cursor: Option<String>,
    /// Maximum messages to return (default 100, max 1000).
    #[serde(default)]
    pub limit: Option<u32>,
    /// When true, advance read cursors past the returned messages.
    #[serde(default)]
    pub mark_read: bool,
    /// Only return messages from the last N hours; defaults to 24. Pass 0 for ALL history.
    #[serde(default)]
    pub since_hours: Option<u32>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `inbox_read`.
#[derive(Debug, Serialize)]
pub(super) struct InboxReadResponse {
    /// Number of messages in this page.
    pub total: usize,
    /// Count of unread messages remaining after this page.
    pub unread: u32,
    /// Front-matter rows across subscribed rooms.
    pub messages: Vec<MessageFrontMatter>,
    /// Opaque cursor for the next page; absent means no more results.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<Cursor>,
}

// ─── inbox_ack ───────────────────────────────────────────────────────────────────────────────

/// Params for `inbox_ack`: advance this agent's per-room read cursors past acked messages.
///
/// Two modes, combinable:
/// * `message_ids` — resolve each id to its `(room, seq)`, then advance each room's cursor to the
///   max acked seq in that room.
/// * `room` + `to_seq` — advance that one room's cursor straight to `to_seq` ("ack everything up
///   to here" / stale-room cleanup).
///
/// At least one mode must be supplied; an empty request is rejected.
#[derive(Debug, Clone, Default, Deserialize, Serialize, schemars::JsonSchema)]
pub struct InboxAckParams {
    /// Message ids to ack (mode a). Empty when only the bulk mode is used.
    #[serde(default)]
    pub message_ids: Vec<String>,
    /// Target room for the bulk `to_seq` mode (mode b).
    #[serde(default)]
    pub room: Option<RoomId>,
    /// Advance `room`'s cursor straight to this seq (mode b). Requires `room`.
    #[serde(default)]
    pub to_seq: Option<u64>,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// One `(room, new_seq)` cursor advance recorded by `inbox_ack`.
#[derive(Debug, Serialize)]
pub(super) struct CursorAdvance {
    /// The room whose per-agent read cursor advanced.
    pub room: String,
    /// The cursor's new seq after the advance.
    pub seq: u64,
}

/// Response for `inbox_ack`.
#[derive(Debug, Serialize)]
pub(super) struct InboxAckResponse {
    /// Number of message ids that resolved and were acked (the bulk `to_seq` mode does not
    /// contribute to this count).
    pub acked: usize,
    /// The `(room, new_seq)` cursor advances this call produced.
    pub cursors_advanced: Vec<CursorAdvance>,
}

// ─── get_or_create_chat_room_for_path ────────────────────────────────────────────────────────

/// Params for `get_or_create_chat_room_for_path`: resolve the repo at `path` to its canonical room
/// (by git remote, else repo path) and join it. Lets an agent coordinate in ANOTHER repo's room.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct GetOrCreateRoomForPathParams {
    /// Filesystem path inside (or naming) the target repo. Resolved to the repo ROOT so every
    /// subdirectory of one repo maps to a single room.
    pub path: String,
    /// Optional sub-identity to act as; defaults to the server's own agent. Lets one orchestrator
    /// drive many named subagents.
    #[serde(default)]
    pub as_agent: Option<String>,
}

/// Response for `get_or_create_chat_room_for_path`.
#[derive(Debug, Serialize)]
pub(super) struct GetOrCreateRoomForPathResponse {
    /// The canonical room id for the target repo (the one agents there auto-join).
    pub room: String,
    /// Short scope label: `remote`, `path`, `session`, or `global`.
    pub scope: String,
    /// Human-readable room title.
    pub title: String,
    /// True when this call created the room; false when it already existed.
    pub created: bool,
}

// ─── dm_send ───────────────────────────────────────────────────────────────────────────────────

/// Params for `dm_send` — a direct message to one agent.
#[derive(Debug, Clone, Deserialize, Serialize, schemars::JsonSchema)]
pub struct DmSendParams {
    /// Recipient agent id. The DM is delivered to this agent's inbox via a private pairwise room
    /// that both ends auto-join.
    pub to_agent: String,
    /// Optional sub-identity to send AS; defaults to the server's own agent. Lets one orchestrator
    /// send on behalf of any subagent it drives.
    #[serde(default)]
    pub as_agent: Option<String>,
    /// Short human subject line.
    pub subject: String,
    /// Message body (markdown). Empty when omitted.
    #[serde(default)]
    pub body: Option<String>,
    /// Id of the message this one replies to, for threading.
    #[serde(default)]
    pub reply_to: Option<String>,
}

/// Response for `dm_send`.
#[derive(Debug, Serialize)]
pub(super) struct DmSendResponse {
    /// The new message id.
    pub message_id: String,
    /// The private pairwise room the DM was delivered to (`dm:<lo>:<hi>`).
    pub room: String,
}