a3s-ahp 2.4.0

Agent Harness Protocol v2.4 — Universal, transport-agnostic protocol for supervising autonomous AI agents
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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! AHP client implementation

use crate::protocol::AgentInfo;
use crate::transport::TransportLayer;
use crate::{
    AhpError, AhpEvent, AhpNotification, AhpRequest, BatchRequest, BatchResponse, Decision,
    EventType, HandshakeRequest, HandshakeResponse, QueryRequest, QueryResponse, Result, Transport,
    TransportConfig, PROTOCOL_VERSION,
};
use serde::de::DeserializeOwned;
use std::sync::Arc;

/// AHP client - sends events to harness server
pub struct AhpClient {
    transport: Arc<dyn TransportLayer>,
    session_id: String,
    agent_id: String,
    _config: TransportConfig,
    handshake_done: std::sync::atomic::AtomicBool,
}

impl AhpClient {
    /// Create a new AHP client with the specified transport
    pub async fn new(transport: Transport) -> Result<Self> {
        Self::new_with_config(transport, TransportConfig::default()).await
    }

    /// Create a new AHP client with the specified transport and transport config.
    pub async fn new_with_config(transport: Transport, config: TransportConfig) -> Result<Self> {
        #[cfg(not(any(
            feature = "stdio",
            feature = "http",
            feature = "websocket",
            feature = "grpc",
            feature = "unix-socket"
        )))]
        {
            let _ = (transport, config);
            return Err(AhpError::UnsupportedCapability(
                "No transport features enabled".to_string(),
            ));
        }

        #[cfg(any(
            feature = "stdio",
            feature = "http",
            feature = "websocket",
            feature = "grpc",
            feature = "unix-socket"
        ))]
        {
            let transport_layer: Arc<dyn TransportLayer> = match transport {
                #[cfg(feature = "stdio")]
                Transport::Stdio { program, args } => Arc::new(
                    crate::transport::stdio::StdioTransport::spawn_with_config(
                        program, &args, &config,
                    )
                    .await?,
                ),

                #[cfg(feature = "http")]
                Transport::Http { url, auth } => Arc::new(
                    crate::transport::http::HttpTransport::new_with_config(url, auth, &config)?,
                ),

                #[cfg(feature = "websocket")]
                Transport::WebSocket { url, auth } => Arc::new(
                    crate::transport::websocket::WebSocketTransport::connect_with_config(
                        url, auth, &config,
                    )
                    .await?,
                ),

                #[cfg(feature = "grpc")]
                Transport::Grpc {
                    endpoint: _,
                    auth: _,
                } => {
                    return Err(AhpError::UnsupportedCapability(
                        "gRPC transport not yet implemented".to_string(),
                    ));
                }

                #[cfg(feature = "unix-socket")]
                Transport::UnixSocket { path } => Arc::new(
                    crate::transport::unix_socket::UnixSocketTransport::connect_with_config(
                        path, &config,
                    )
                    .await?,
                ),

                #[allow(unreachable_patterns)]
                _ => {
                    return Err(AhpError::UnsupportedCapability(
                        "Transport not enabled".to_string(),
                    ))
                }
            };

            Ok(Self {
                transport: transport_layer,
                session_id: uuid::Uuid::new_v4().to_string(),
                agent_id: uuid::Uuid::new_v4().to_string(),
                _config: config,
                handshake_done: std::sync::atomic::AtomicBool::new(false),
            })
        }
    }

    /// Create a new AHP client with a pre-configured transport layer (for testing).
    ///
    /// This bypasses transport selection logic and uses the provided transport directly.
    /// Test clients are treated as handshaken so unit tests can focus on transport behavior.
    pub fn new_for_testing(transport: Arc<dyn TransportLayer>) -> Self {
        Self {
            transport,
            session_id: uuid::Uuid::new_v4().to_string(),
            agent_id: uuid::Uuid::new_v4().to_string(),
            _config: TransportConfig::default(),
            handshake_done: std::sync::atomic::AtomicBool::new(true),
        }
    }

    /// Perform handshake with harness server
    ///
    /// # Arguments
    ///
    /// * `capabilities` - List of capability strings the agent supports
    ///
    pub async fn handshake(&self, capabilities: Vec<String>) -> Result<HandshakeResponse> {
        let request = HandshakeRequest {
            protocol_version: PROTOCOL_VERSION.to_string(),
            agent_info: AgentInfo {
                framework: "a3s-ahp".to_string(),
                version: env!("CARGO_PKG_VERSION").to_string(),
                capabilities,
            },
            session_id: self.session_id.clone(),
            agent_id: self.agent_id.clone(),
        };

        let result = self
            .send_rpc_request(
                "ahp/handshake",
                serde_json::to_value(&request)?,
                "Handshake",
            )
            .await?;
        let handshake_response: HandshakeResponse = serde_json::from_value(result)?;

        self.handshake_done
            .store(true, std::sync::atomic::Ordering::Release);

        Ok(handshake_response)
    }

    /// Send an event and wait for decision (blocking events only).
    ///
    /// Returns the raw JSON decision payload. Callers should use the event type
    /// to deserialize into the appropriate specialized decision type.
    pub async fn send_event(
        &self,
        event_type: EventType,
        payload: serde_json::Value,
    ) -> Result<serde_json::Value> {
        self.ensure_handshake()?;

        let event = AhpEvent {
            event_type,
            session_id: self.session_id.clone(),
            agent_id: self.agent_id.clone(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            depth: 0,
            payload,
            context: None,
            metadata: None,
        };

        if event_type.is_blocking() {
            self.send_rpc_request("ahp/event", serde_json::to_value(&event)?, "Event")
                .await
        } else {
            // Fire-and-forget notification
            let notification = AhpNotification::new("ahp/event", serde_json::to_value(&event)?);
            self.transport.send_notification(notification).await?;

            // Return default allow decision for notifications
            Ok(serde_json::json!({"decision": "allow"}))
        }
    }

    /// Send an event and deserialize the response as the generic AHP decision.
    ///
    /// Use `send_typed_event` for harness points that return specialized decision
    /// shapes such as `ContextPerceptionDecision`.
    pub async fn send_event_decision(
        &self,
        event_type: EventType,
        payload: serde_json::Value,
    ) -> Result<Decision> {
        let value = self.send_event(event_type, payload).await?;
        Ok(serde_json::from_value(value)?)
    }

    /// Send an event and deserialize the response into a caller-selected type.
    pub async fn send_typed_event<T>(
        &self,
        event_type: EventType,
        payload: serde_json::Value,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let value = self.send_event(event_type, payload).await?;
        Ok(serde_json::from_value(value)?)
    }

    /// Send a complete event and return the raw decision payload.
    ///
    /// Unlike `send_event`, this method preserves the caller-provided
    /// `session_id`, `agent_id`, `depth`, `context`, and `metadata`.
    pub async fn send_event_full_value(&self, event: &AhpEvent) -> Result<serde_json::Value> {
        self.ensure_handshake()?;

        if event.event_type.is_blocking() {
            self.send_rpc_request("ahp/event", serde_json::to_value(event)?, "Event")
                .await
        } else {
            // Fire-and-forget notification
            let notification = AhpNotification::new("ahp/event", serde_json::to_value(event)?);
            self.transport.send_notification(notification).await?;

            // Return default allow decision for notifications
            Ok(serde_json::json!({"decision": "allow"}))
        }
    }

    /// Send a complete event (with context) and deserialize a generic decision.
    ///
    /// Use `send_typed_event_full` for harness points that return specialized
    /// decision shapes such as `ContextPerceptionDecision`.
    pub async fn send_event_full(&self, event: &AhpEvent) -> Result<Decision> {
        let value = self.send_event_full_value(event).await?;
        Ok(serde_json::from_value(value)?)
    }

    /// Send a complete event and deserialize the response into a selected type.
    pub async fn send_typed_event_full<T>(&self, event: &AhpEvent) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let value = self.send_event_full_value(event).await?;
        Ok(serde_json::from_value(value)?)
    }

    /// Send a query to the harness
    pub async fn query(
        &self,
        query_type: impl Into<String>,
        payload: serde_json::Value,
    ) -> Result<QueryResponse> {
        self.ensure_handshake()?;

        let query = QueryRequest {
            session_id: self.session_id.clone(),
            agent_id: self.agent_id.clone(),
            query_type: query_type.into(),
            payload,
        };

        let result = self
            .send_rpc_request("ahp/query", serde_json::to_value(&query)?, "Query")
            .await?;
        let query_response: QueryResponse = serde_json::from_value(result)?;

        Ok(query_response)
    }

    /// Send a batch of events
    pub async fn send_batch(&self, events: Vec<AhpEvent>) -> Result<BatchResponse> {
        self.ensure_handshake()?;

        if let Some(event) = events.iter().find(|event| !event.event_type.is_batchable()) {
            return Err(AhpError::Protocol(format!(
                "Batch failed: event type {} cannot be batched because it does not return a generic Decision",
                event.event_type
            )));
        }

        let event_count = events.len();
        let batch = BatchRequest { events };

        let result = self
            .send_rpc_request("ahp/batch", serde_json::to_value(&batch)?, "Batch")
            .await?;
        let batch_response: BatchResponse = serde_json::from_value(result)?;

        if batch_response.decisions.len() != event_count {
            return Err(AhpError::Protocol(format!(
                "Batch failed: decision count mismatch, expected {}, got {}",
                event_count,
                batch_response.decisions.len()
            )));
        }

        Ok(batch_response)
    }

    /// Close the client connection
    pub async fn close(&self) -> Result<()> {
        self.transport.close().await
    }

    fn ensure_handshake(&self) -> Result<()> {
        if self
            .handshake_done
            .load(std::sync::atomic::Ordering::Acquire)
        {
            Ok(())
        } else {
            Err(AhpError::Protocol(
                "Handshake must complete before sending AHP operations".to_string(),
            ))
        }
    }

    async fn send_rpc_request(
        &self,
        method: impl Into<String>,
        params: serde_json::Value,
        operation: &str,
    ) -> Result<serde_json::Value> {
        let request = AhpRequest::new(method, params);
        let request_id = request.id.clone();
        let response = self.transport.send_request(request).await?;

        if response.jsonrpc != "2.0" {
            return Err(AhpError::Protocol(format!(
                "{} failed: invalid JSON-RPC version {}",
                operation, response.jsonrpc
            )));
        }

        if response.id != request_id {
            return Err(AhpError::Protocol(format!(
                "{} failed: response id mismatch, expected {}, got {}",
                operation, request_id, response.id
            )));
        }

        if let Some(error) = response.error {
            return Err(AhpError::Protocol(format!(
                "{} failed: {}",
                operation, error.message
            )));
        }

        response
            .result
            .ok_or_else(|| AhpError::Protocol(format!("{} failed: missing result", operation)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::{
        AhpResponse, BatchResponse, ContextPerceptionDecision, EventContext, Fact, InjectedContext,
        SessionStats,
    };
    use async_trait::async_trait;
    use std::sync::Mutex;

    struct StaticTransport {
        response: AhpResponse,
        echo_request_id: bool,
    }

    #[async_trait]
    impl TransportLayer for StaticTransport {
        async fn send_request(&self, request: AhpRequest) -> Result<AhpResponse> {
            let mut response = self.response.clone();
            if self.echo_request_id {
                response.id = request.id;
            }
            Ok(response)
        }

        async fn send_notification(&self, _notification: AhpNotification) -> Result<()> {
            Ok(())
        }

        async fn close(&self) -> Result<()> {
            Ok(())
        }
    }

    struct RecordingTransport {
        response: AhpResponse,
        last_request_params: Mutex<Option<serde_json::Value>>,
    }

    #[async_trait]
    impl TransportLayer for RecordingTransport {
        async fn send_request(&self, request: AhpRequest) -> Result<AhpResponse> {
            *self.last_request_params.lock().unwrap() = Some(request.params.clone());
            let mut response = self.response.clone();
            response.id = request.id;
            Ok(response)
        }

        async fn send_notification(&self, notification: AhpNotification) -> Result<()> {
            *self.last_request_params.lock().unwrap() = Some(notification.params.clone());
            Ok(())
        }

        async fn close(&self) -> Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn send_typed_event_preserves_specialized_decision_payload() {
        let decision = ContextPerceptionDecision::Allow {
            injected_context: InjectedContext {
                facts: vec![Fact {
                    content: "workspace uses Rust".to_string(),
                    source: "test".to_string(),
                    confidence: 0.9,
                }],
                file_contents: None,
                project_summary: None,
                knowledge: None,
                suggestions: None,
            },
            metadata: None,
        };
        let transport = Arc::new(StaticTransport {
            response: AhpResponse::success("placeholder", serde_json::to_value(decision).unwrap()),
            echo_request_id: true,
        });
        let client = AhpClient::new_for_testing(transport);

        let response: ContextPerceptionDecision = client
            .send_typed_event(EventType::ContextPerception, serde_json::json!({}))
            .await
            .expect("typed decision should deserialize");

        match response {
            ContextPerceptionDecision::Allow {
                injected_context, ..
            } => {
                assert_eq!(injected_context.facts[0].content, "workspace uses Rust");
            }
            other => panic!("expected allow decision, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn send_event_full_value_preserves_event_context() {
        let transport = Arc::new(RecordingTransport {
            response: AhpResponse::success("placeholder", serde_json::json!({"decision": "allow"})),
            last_request_params: Mutex::new(None),
        });
        let client = AhpClient::new_for_testing(transport.clone());
        let event = AhpEvent {
            event_type: EventType::PreAction,
            session_id: "session-1".to_string(),
            agent_id: "agent-1".to_string(),
            timestamp: "2026-05-01T00:00:00Z".to_string(),
            depth: 2,
            payload: serde_json::json!({"tool": "bash"}),
            context: Some(EventContext {
                session_stats: Some(SessionStats {
                    total_actions: 3,
                    total_tokens: 42,
                    duration_ms: 1000,
                    error_count: 0,
                }),
                current_task: Some("refactor".to_string()),
                ..EventContext::default()
            }),
            metadata: None,
        };

        client
            .send_event_full_value(&event)
            .await
            .expect("full event should send");

        let params = transport
            .last_request_params
            .lock()
            .unwrap()
            .clone()
            .expect("request params should be recorded");
        assert_eq!(params["session_id"], "session-1");
        assert_eq!(params["agent_id"], "agent-1");
        assert_eq!(params["depth"], 2);
        assert_eq!(params["context"]["current_task"], "refactor");
        assert_eq!(params["context"]["session_stats"]["total_tokens"], 42);
    }

    #[tokio::test]
    async fn send_event_rejects_mismatched_response_id() {
        let transport = Arc::new(StaticTransport {
            response: AhpResponse::success("wrong-id", serde_json::json!({"decision": "allow"})),
            echo_request_id: false,
        });
        let client = AhpClient::new_for_testing(transport);

        let error = client
            .send_event(EventType::PreAction, serde_json::json!({}))
            .await
            .expect_err("mismatched response id should fail");

        assert!(error.to_string().contains("response id mismatch"));
    }

    #[tokio::test]
    async fn send_event_requires_handshake() {
        let transport = Arc::new(StaticTransport {
            response: AhpResponse::success("placeholder", serde_json::json!({"decision": "allow"})),
            echo_request_id: true,
        });
        let client = AhpClient {
            transport,
            session_id: "session-1".to_string(),
            agent_id: "agent-1".to_string(),
            _config: TransportConfig::default(),
            handshake_done: std::sync::atomic::AtomicBool::new(false),
        };

        let error = client
            .send_event(EventType::PreAction, serde_json::json!({}))
            .await
            .expect_err("event should fail before handshake");

        assert!(error.to_string().contains("Handshake must complete"));
    }

    #[tokio::test]
    async fn send_batch_rejects_decision_count_mismatch() {
        let transport = Arc::new(StaticTransport {
            response: AhpResponse::success(
                "placeholder",
                serde_json::to_value(BatchResponse { decisions: vec![] }).unwrap(),
            ),
            echo_request_id: true,
        });
        let client = AhpClient::new_for_testing(transport);
        let event = AhpEvent {
            event_type: EventType::PreAction,
            session_id: "session-1".to_string(),
            agent_id: "agent-1".to_string(),
            timestamp: "2026-05-01T00:00:00Z".to_string(),
            depth: 0,
            payload: serde_json::json!({}),
            context: None,
            metadata: None,
        };

        let error = client
            .send_batch(vec![event])
            .await
            .expect_err("batch decision count mismatch should fail");

        assert!(error.to_string().contains("decision count mismatch"));
    }

    #[tokio::test]
    async fn send_batch_rejects_specialized_decision_events() {
        let transport = Arc::new(StaticTransport {
            response: AhpResponse::success(
                "placeholder",
                serde_json::to_value(BatchResponse { decisions: vec![] }).unwrap(),
            ),
            echo_request_id: true,
        });
        let client = AhpClient::new_for_testing(transport);
        let event = AhpEvent {
            event_type: EventType::ContextPerception,
            session_id: "session-1".to_string(),
            agent_id: "agent-1".to_string(),
            timestamp: "2026-05-01T00:00:00Z".to_string(),
            depth: 0,
            payload: serde_json::json!({}),
            context: None,
            metadata: None,
        };

        let error = client
            .send_batch(vec![event])
            .await
            .expect_err("specialized decision event should not be batchable");

        assert!(error.to_string().contains("cannot be batched"));
    }
}