car-proto 0.14.0

JSON-RPC protocol types for Common Agent Runtime client-server communication
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
//! JSON-RPC 2.0 protocol types for CAR client-server communication.
//!
//! The protocol is bidirectional over WebSocket:
//! - Client → Server: session.init, tools.register, proposal.submit, verify
//! - Server → Client: tools.execute (callback for tool execution)
//! - Server → Client: execution.event (notifications)

pub mod daemon;

use car_ir::ActionProposal;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// Tool definition sent by client during registration.
///
/// Mirrors `car_ir::ToolSchema` over the wire so the validator,
/// caching, and rate-limiting layers see the same fields the in-process
/// engine does. New optional fields are added with serde defaults so
/// pre-v0.5.x clients (which only sent `name` / `description` /
/// `parameters`) still parse cleanly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    pub name: String,
    #[serde(default)]
    pub description: String,
    /// JSON Schema for parameters. Empty object = schemaless (legacy
    /// behavior — validator skips type checks).
    #[serde(default)]
    pub parameters: Value,
    /// JSON Schema for return value (optional).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returns: Option<Value>,
    /// Marks the tool as safe to cache/retry.
    #[serde(default)]
    pub idempotent: bool,
    /// If set, results are cached with this TTL in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_ttl_secs: Option<u64>,
    /// If set, rate-limited to this many calls per interval.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_limit: Option<ToolRateLimit>,
}

/// Mirror of `car_ir::ToolRateLimit` over the wire.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolRateLimit {
    pub max_calls: u32,
    pub interval_secs: f64,
}

// --- Client → Server requests ---

/// Initialize a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInitRequest {
    pub client_id: String,
    #[serde(default)]
    pub tools: Vec<ToolDefinition>,
    #[serde(default)]
    pub policies: Vec<PolicyDefinition>,
}

/// Policy definition from client.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyDefinition {
    pub name: String,
    pub rule: String, // deny_tool, deny_tool_param, require_state, etc.
    #[serde(default)]
    pub target: String,
    #[serde(default)]
    pub key: String,
    #[serde(default)]
    pub value: Value,
    #[serde(default)]
    pub pattern: String,
}

/// Submit a proposal for execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProposalSubmitRequest {
    pub proposal: ActionProposal,
}

/// Verify a proposal without executing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyRequest {
    pub proposal: ActionProposal,
    #[serde(default)]
    pub initial_state: HashMap<String, Value>,
}

// --- Server → Client callbacks ---

/// Server asks client to execute a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecuteRequest {
    pub action_id: String,
    pub tool: String,
    pub parameters: Value,
    #[serde(default)]
    pub timeout_ms: Option<u64>,
    #[serde(default)]
    pub attempt: u32,
}

/// Client returns tool execution result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecuteResponse {
    pub action_id: String,
    #[serde(default)]
    pub output: Option<Value>,
    #[serde(default)]
    pub error: Option<String>,
}

// --- Server → Client notifications ---

/// Execution event notification (streaming).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionEvent {
    pub kind: String, // matches EventKind values
    #[serde(default)]
    pub action_id: Option<String>,
    #[serde(default)]
    pub proposal_id: Option<String>,
    #[serde(default)]
    pub data: HashMap<String, Value>,
}

// --- Host UI protocol ---

/// OS-host-visible agent status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HostAgentStatus {
    Idle,
    Running,
    WaitingForApproval,
    Paused,
    Completed,
    Errored,
    Stopped,
}

/// Host-visible display hints for an agent.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HostAgentDisplay {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accent: Option<String>,
}

/// Agent entry visible to menu bar, tray, or terminal host clients.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostAgent {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    pub status: HostAgentStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_task: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default)]
    pub display: HostAgentDisplay,
    pub updated_at: DateTime<Utc>,
    #[serde(default)]
    pub metadata: Value,
}

/// Request to register an agent with the OS host surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterHostAgentRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default)]
    pub display: HostAgentDisplay,
    #[serde(default)]
    pub metadata: Value,
}

/// Request to update an agent's host-visible status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetHostAgentStatusRequest {
    pub agent_id: String,
    pub status: HostAgentStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_task: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(default)]
    pub payload: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HostApprovalStatus {
    Pending,
    Resolved,
}

/// Approval request visible to the OS host surface.
///
/// `client_id` is the WS session that raised the approval. When
/// `Some(x)`, only session `x` may call `host.resolve_approval` on
/// it — added 2026-05 after a security audit found unrestricted
/// resolve let one client approve another's pending request. When
/// `None` the approval is system-raised (the high-risk-method
/// approval gate uses this so the local UI session can resolve
/// approvals raised by *other* sessions' dispatch attempts) and
/// any authenticated session may resolve it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostApprovalRequest {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    pub action: String,
    pub details: Value,
    #[serde(default)]
    pub options: Vec<String>,
    pub status: HostApprovalStatus,
    pub created_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution: Option<String>,
}

/// Request to create an approval prompt in the host surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateHostApprovalRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    pub action: String,
    #[serde(default)]
    pub details: Value,
    #[serde(default)]
    pub options: Vec<String>,
    /// When `true`, the approval is created as system-level: it has
    /// no `client_id` owner and any authenticated session may resolve
    /// it. This is the right mode for agent-requested approvals where
    /// "the user" (via CarHost or `car-host approve`) is the resolver,
    /// not the requesting agent itself. The previous default (always
    /// session-owned by the requester) locked the approval to the
    /// agent's WS connection, which broke as soon as the agent
    /// reconnected — the new session got a fresh client_id and could
    /// no longer resolve its own pending approval, AND CarHost (a
    /// different session) couldn't either.
    ///
    /// Defaults to `false` for backward compatibility: existing
    /// callers that don't set this field keep the strict per-session
    /// ownership semantics.
    #[serde(default)]
    pub system_level: bool,
}

/// Request to resolve an approval.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolveHostApprovalRequest {
    pub approval_id: String,
    pub resolution: String,
}

/// Host event emitted to subscribed OS host clients.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostEvent {
    pub id: String,
    pub timestamp: DateTime<Utc>,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    pub message: String,
    #[serde(default)]
    pub payload: Value,
}

/// Manifest-lock relationship for the daemon serving this WS.
/// Returned inside [`HostIdentity`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HostManifestRole {
    /// This daemon holds the exclusive `<manifest>.lock` — agents.*
    /// mutations route through here.
    Owner,
    /// Another `car-server` on the host owns the lock; this daemon
    /// runs in observe-only mode (Parslee-ai/car-releases#44).
    Observer,
    /// No manifest is configured at all — `HOME` unset or the
    /// embedder didn't install one.
    None,
}

/// Daemon-identifying metadata returned inside [`HostSnapshot`].
/// Lets multi-daemon hosts (`car-server install` plus an ad-hoc
/// eval daemon, etc.) tell which daemon they connected to and
/// whether THIS one owns the supervisor lock or is observe-only.
/// Closes the observability gap from Parslee-ai/car-releases#44.
///
/// Stable on the wire across the connection's lifetime — emitted
/// once on subscribe rather than as a periodic event because the
/// fields are immutable for the daemon's lifetime (the manifest
/// role flips only on daemon restart, which would close this WS
/// anyway).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostIdentity {
    /// `CARGO_PKG_VERSION` from the daemon binary at build time.
    pub version: String,
    /// `std::process::id()` of the daemon — operators correlating
    /// log lines + `ps`/`lsof` output need this.
    pub pid: u32,
    /// Absolute path to the lifecycle-agent manifest this daemon
    /// supervises (or observes). `None` when no manifest is
    /// configured (`HOME` unset; embedder didn't install one).
    /// Lossy-encoded on non-UTF-8 paths — operators on path
    /// layouts that round-trip through this field should normalize
    /// upstream.
    pub manifest_path: Option<String>,
    pub manifest_role: HostManifestRole,
    /// Parslee cloud account bound to this daemon, when the local user
    /// has completed `car auth login`. This is advisory identity for
    /// cloud-backed features; the local WS auth token still gates access
    /// to the daemon process.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parslee: Option<ParsleeIdentity>,
}

/// Parslee cloud identity associated with the local CAR user.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsleeIdentity {
    pub account_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_organization: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub organization_name: Option<String>,
}

/// Snapshot returned by `host.subscribe`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostSnapshot {
    pub subscribed: bool,
    #[serde(default)]
    pub agents: Vec<HostAgent>,
    #[serde(default)]
    pub approvals: Vec<HostApprovalRequest>,
    #[serde(default)]
    pub events: Vec<HostEvent>,
    /// Daemon-identifying metadata — added 2026-05 to surface
    /// observe-only mode (Parslee-ai/car-releases#44) and let
    /// multi-daemon hosts tell which daemon they're talking to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<HostIdentity>,
}

// --- Response types ---

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInitResponse {
    pub session_id: String,
    pub tools_registered: usize,
    pub policies_registered: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyResponse {
    pub valid: bool,
    pub issues: Vec<VerifyIssueProto>,
    pub simulated_state: HashMap<String, Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyIssueProto {
    pub action_id: String,
    pub severity: String,
    pub message: String,
}

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

    #[test]
    fn tool_definition_roundtrip() {
        let td = ToolDefinition {
            name: "search".to_string(),
            description: "Search the web".to_string(),
            parameters: serde_json::json!({"type": "object", "properties": {"query": {"type": "string"}}}),
            returns: None,
            idempotent: false,
            cache_ttl_secs: None,
            rate_limit: None,
        };
        let json = serde_json::to_string(&td).unwrap();
        let rt: ToolDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.name, "search");
    }

    #[test]
    fn tool_definition_back_compat_pre_v05_clients() {
        // Pre-v0.5 clients only sent these three fields. The new
        // optional fields must default cleanly so the wire stays
        // backward-compatible.
        let legacy = r#"{"name":"read","description":"","parameters":{}}"#;
        let td: ToolDefinition = serde_json::from_str(legacy).unwrap();
        assert_eq!(td.name, "read");
        assert!(td.returns.is_none());
        assert!(!td.idempotent);
        assert!(td.cache_ttl_secs.is_none());
        assert!(td.rate_limit.is_none());
    }

    #[test]
    fn tool_execute_request_roundtrip() {
        let req = ToolExecuteRequest {
            action_id: "a1".to_string(),
            tool: "search".to_string(),
            parameters: serde_json::json!({"query": "rust"}),
            timeout_ms: Some(5000),
            attempt: 1,
        };
        let json = serde_json::to_string(&req).unwrap();
        let rt: ToolExecuteRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.tool, "search");
        assert_eq!(rt.timeout_ms, Some(5000));
    }

    #[test]
    fn tool_execute_response_success() {
        let resp = ToolExecuteResponse {
            action_id: "a1".to_string(),
            output: Some(Value::from("results")),
            error: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("results"));
    }

    #[test]
    fn tool_execute_response_error() {
        let resp = ToolExecuteResponse {
            action_id: "a1".to_string(),
            output: None,
            error: Some("timeout".to_string()),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("timeout"));
    }

    #[test]
    fn session_init_request() {
        let req = SessionInitRequest {
            client_id: "client-1".to_string(),
            tools: vec![ToolDefinition {
                name: "read".to_string(),
                description: "Read file".to_string(),
                parameters: serde_json::json!({}),
                returns: None,
                idempotent: false,
                cache_ttl_secs: None,
                rate_limit: None,
            }],
            policies: vec![],
        };
        let json = serde_json::to_string(&req).unwrap();
        let rt: SessionInitRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.tools.len(), 1);
    }

    #[test]
    fn verify_request() {
        let req = VerifyRequest {
            proposal: ActionProposal {
                id: "p1".to_string(),
                source: "test".to_string(),
                actions: vec![],
                timestamp: chrono::Utc::now(),
                context: HashMap::new(),
            },
            initial_state: [("x".to_string(), Value::from(1))].into(),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("p1"));
    }
}